For each loop using Java Iterator [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
So I've been looking over some java code that i understand is used for a foreach loop but it seems like it is overly complicated.
I have a Control.java file that contains properties.
I have a Controls.java file that uses Iterator and takes Control as the data type.
public class Controls implements Iterable<Control>{
protected ArrayList<Control> controls;
public Controls()
{
controls = new ArrayList<Control>();
}
public Controls(ArrayList<Control> controls)
{
this.controls = controls;
}
public ArrayList<Control> value()
{
return controls;
}
public void add(Control ctrl)
{
this.controls.add(ctrl);
}
public void add(Controls ctrls)
{
for(Control ctrl : ctrls)
{
this.controls.add(ctrl);
}
}
public void remove(Control ctrl)
{
if(this.controls.contains(ctrl))
{
this.controls.remove(ctrl);
} else
{
for (Control c: this.controls)
{
if(c instanceof ContainerControl)
{
((ContainerControl)c).controls.remove(ctrl);
}
}
}
}
public Control get(String name)
{
//stuff here
}
#Override
public Iterator<Control> iterator() {
return controls.iterator();
}
}
Other files use it as such:
public void dumpInstantiation(StringBuffer buf)
{
for(Control control : controls)
{
control.dumpInstantiation(buf);
}
}
To my understanding this is just a foreach loop with the added benefit of adding or removing (or calling any other method) as each control is iterated. As a java newbie a couple questions come to mind though:
Is there an easier way to implement this? Is this how it is usually done?
Is there any other benefits of doing it this way?
Is there a way to do this without ArrayList and Iterator?

Is there an easier way to implement this? Is this how it is usually done?
In order to use the Java foreach construct, your class needs to implement the Iterable interface, and provide enough functionality within the required methods to "iterate" over the list and return each item. Usually this means you need to know when there are items remaining and a way to return each one in step. The interface API will tell you if a method is "required" (ie: the method must be declared, but it can provide no implementation) or not. An easier method would be to leverage an already existing collection type, so you don't have to make your own.
Is there any other benefits of doing it this way?
It's a good way to provide a nice method to allow users to iterate over your list, and it makes the class compatible with other interfaces that operate on Iterable
Is there a way to do this without ArrayList and Iterator?
You could wrap your class in an existing collection that already implements iterator, but this will be up to you.

So, a for-each loop has two 'arguments'.
 1. the variable to which is assigned the value of each item of an array one by one.
 2. the array or ArrayList etc.
An example:
public class Test {
public static void main(String[] args) {
int[] numbers = new int[] {3,8,5,2};
for (int i : numbers)
System.out.println(i);
}
}
Prints:
3
8
5
2
You see, it's not that difficult!
And, instead of a normal array, you could use the ArrayList class to dynamically add/remove items:
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(3);
numbers.add(8);
numbers.add(5);
numbers.add(2);
for (int i : numbers)
System.out.println(i);
}
}
Prints the same.
Did this answer your question?

Related

Java: How I can improve this cod e? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I made this, basically the user can toggle options to be able to see them or not in the application, i wanted to know how i can improve this class. there are parts like SEARCH & MAP that only change the value in the map and nothing else, would be better to create an abstract class and extend for each type? TypeWithoutToggle (this will only change the value in the map for the type and implement empty #toggle)) TypeWithToggle.. then extend these depending.
public enum ToggleType {
NAME {
#Override
public void toggle(VideoPlayer videoPlayer) {
videoPlayer.doToggleName();
}
},
EDITOR {
#Override
public void toggle(VideoPlayer videoPlayer) {
if (videoPlayer.isTrue("EDITOR"))
videoPlayer.createEditors();
else
videoPlayer.deleteEditors();
}
},
SEARCH {
#Override
public void toggle(VideoPlayer videoPlayer) {
}
},
MAP {
#Override
public void toggle(VideoPlayer videoPlayer) {
// handle on {#link VideoPlayer#create()}
}
},
protected abstract void toggle(VideoPlayer videoPlayer);
public void run(VideoPlayer videoPlayer) {
videoPlayer.toggleMap.put(name(), !videoPlayer.isTrue(name()));
toggle(videoPlayer);
}
You should not expose the toggleMap attribute on VideoPlayer class. Instead the should be encapsulated as a method in VideoPlayer class.
It's difficult to give a more detailed comment only by looking at these few lines.
This question is mostly opinion based, but there are at least two things that I could mention:
First is you are coupling VideoPlayer with ToggleType. There should be a separate method, probably in VideoPlayer (or a VideoPlayerToggler), that is responsible for the toggle that accepts ToggleType.
Example:
switch(toggleType):
case NAME:
doToggleName()
break;
case EDITOR:
if (videoPlayer.isTrue("EDITOR"))
videoPlayer.createEditors();
else
videoPlayer.deleteEditors();
break;
...
Let's assume that you will add a new component that can be toggled, like a MenuComponent. So it might scale better, and decouples your code. With your approach, you would have to add another abstract method, that will handle your type. In short- ToggleType doesn't have to know what or how to toggle. There might be many toggle handlers depending on your environment, configuration or other factors.
Secondly if you put this method inside VideoPlayer, then you don't have to expose any methods, keep everything well encapsulated and private, which is a good idea in general.

A good way to proof to my teacher that java streams can have worse performance than a simple for [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
My teacher is convinced that it is convenient to use streams when looping over a list because operations can be parallelized.
I understand that this is true in some ways, but I think that we could always implement a faster code writing it by ourselves.
We are talking here of use cases where we want to optimize as much as we can.
Suppose that we start with the following code:
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class HelloWorld{
public static void main (String args[]) {
List<Something> ls = new ArrayList<Something>();
ls.add(new Something(true));
ls.add(new Something(false));
System.out.println("Active things: " + getActive(ls).size());
}
public static List<Something> getActive(List<Something> listOfThings){
return listOfThings != null? listOfThings.stream().filter(t -> t.isActive()).collect(Collectors.toList()): null;
}
public static class Something {
public Something(boolean active) {
this.active = active;
}
private boolean active;
public boolean isActive() {
return active;
}
public void justDoIt() {
System.out.println("done");
}
}
}
Isn't true that, the method getActive() can be optimized avoiding the use of streams ?
I understand that it is easier to use streams, but because they have to be general purpose, they will never be faster than well written and optimized code.
For example, if the list is very big and we know that it would be convenient to parallelize the loop on three cores, couldn't we just execute in three different threads the loop with a standard iterator?

How to check if an enum value changed? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm new to Java and development and don't know how to do most of the stuff. So I wanter to ask you guys how to check if an enum value changed. So I have this:
public enum GameState {
WAITING,
INTRO,
INTRO_WAIT,
INTRO_1,
INTRO_1_WAIT,
LOBBY_INTRO,
LOBBY,
INTRO_GAME1,
GAME1,
INTRO_GAME2,
GAME2;
}
So I want to know how to detect if an enum value changed from any of those to any of those. Hope you know what I'm try to say.
Thanks :)
I assume you mean that some other class has a field GameState state, and you want to know when it changes from one value to another.
There's not an "automatic" way to do that. Have that other class make that field be private (which is a good idea anyway), and any time it changes it (for instance, via a setState(GameState) method, it can perform whatever action you want — such as calling any GameStateListener that's been registered with that class, or whatever checking mechanism you want.
It might look something like this:
public interface GameStateListener {
void onChange(GameState changingFrom, GameState changingTo);
}
public class Game {
private GameState state = WAITING; // or whatever initial value
private final Collection<GameStateListener> listeners = new ArrayList<>();
public void registerListener(GameStateListener listener) {
listeners.add(listener);
}
public void changeState(GameState newState) {
for (GameStateListener listener : listeners) {
listener.onChange(state, newState);
}
this.state = newState;
}
...
}
Note that that code is not thread-safe, and making it be thread-safe would add a good deal of complexity. There are other ways to do it, too, but the above is a pretty standard pattern.

Only 5 instances of a class [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I want to have only 5 instance of a class throughout the application life time. How can I achieve this? Please give sample code, if possible.
As Singletons shall be made with enums (See "Effective Java"):
public enum FiveInstance {
INSTANCE1, INSTANCE2, INSTANCE3, INSTANCE4, INSTANCE5;
public void anyMethod() {}
}
Greetz GHad
The Factory pattern could be your friend. One (fictional, not threadsafe and thus quite simple) example to illustrate the approach:
public static MartiniFactory {
private static int olives = 100; // you asked for '5' but 100 is more realistic
// for this example.
public static Drink createMartini() throws OutOfOlivesException {
if (olives > 0) {
olives--;
return new Martini(new Gin(4), new Vermouth(1), new Olive());
else {
throw new OutOfOlivesException();
}
}
// forgot to mention, only the factory (=bar) is able to create Martinis, so:
private class Martini {
Martini(Ingredient... ingredients) {
// ...
}
// ....
}
}
EDIT
The license example was not too good - so I moved it to a domain that expects, that objects created by the factory are not returned and destroyed without noticing the factory. The Bar can't create Martinis when there is no olive left and it definitly doesn't want the drink back after it has been consumed ;-)
EDIT 2
And for sure, only the factory can create Instances (=Drinks).
(No guarantee, that the added inner private class fulfills this requirement, don't have
an IDE at hand to do a quick test .. feel free to comment or edit)
class Sample
{
private static int i = 0;
private Sample()
{
}
public static Sample CreateInstance()
{
if(i <5)
{
i++;
return new Sample();
}
else
throw new Exception("Can not create more then 5 instance of this class");
}
}
Have a look at the static keyword.
public class FiveInstance {
private static int instanceCount = 0;
private FiveInstance(){
}
public static FiveInstance getNewInstance() throws InstanceExceededException{
if(instanceCount < 5){
instanceCount++;
return new FiveInstance();
}else{
throw new InstanceExceededException();
}
}
}
Create a private static member to count the instances of the class. Then, make sure every constructor of your class increment this static variable and test for overflow. If you have more than one constructor I suggest that you make one constructor implement this behaviour and the others should call it. The behavior of the constructor upon an attempt to create a sixth instance is up to you. Maybe you want to throw an Exception.
You can try following code but written in C#, you can get a basic idea how can it be done.
public class MultiTone
{
private static MultiTone _cache;
private static int _counter=5;
MultiTone()
{
}
public static MultiTone GetInstance()
{
if(_counter==0)
{
return _cache ?? (_cache = new MultiTone());
}
_counter--;
return new MultiTone();
}
}
And mind that this class is't intended to use in multi-threading environment.
I think you can't. You can force that if somebody want to create or destroy an instance has to use these static methods:
import java.util.*;
public class Fiveton {
public final static int MAX_INSTANCES = 5;
private static List<Fiveton> instances = new ArrayList<Fiveton>();
private Fiveton() { }
public static Fiveton getInstance() {
if (instances.size()>=MAX_INSTANCES) throw new RuntimeException("Hey! You've reached the maximum of instances: " + MAX_INSTANCES);
Fiveton instance = new Fiveton();
instances.add(instance);
return instance;
}
public static void destroy(Fiveton instance) {
instances.remove(instance);
}
}
The problem is method destroy. You can't be sure that someone is still referencing the destroyed object.
There is a pattern called a Multiton which deals with this, as an extension of Singleton. Nobody seems quite clear it it's a pattern in its own right or a variation on Singleton. Check out the link, it includes sample code.
Look at Object pool pattern. Its java implementation is greatly described in Grand Patterns in Java V1.
Short description from the book overview:
Object Pool
Manage the reuse of objects for a type
of object that is expensive to create
or only a limited number of a kind of
object can be created.
Create a static field called howMany which will be incremented each time that the constructor is called.
When howMany is => 5, deny creation of the object.

Monitor changes to a collection

Say you have the following java bean:
public class MyBean
{
private List<String> names = new ArrayList<String>();
public void addName(String name)
{
names.add(name);
fireNamesPropertyChange(name);
}
}
How would you normally implement a property change event for a collection? Do you try and use the index property which seems to be more for arrays than collections?
(NOTE: I updated this post after realizing a few mistakes of my own so this isn't the original but a more refined one instead)
For this purpose I'd do two new interfaces, ListListener and Listenable and then I would create a new class like ListenableArrayList which would wrap every List method with a call to one (or more) relevant methods defined in ListListener. In code it'd be something like this:
public class ListenableArrayList<T> extends ArrayList<T>
implements Listenable<T> {
private ArrayList<T> internalList;
private ListListener<T> listener;
/* .. */
public void add(T item) {
listener.beforeAdd(T item);
internalList.add(item);
listener.afterAdd(T item);
}
/* .. */
public void setListener(ListListener<T> listener) {
this.listener = listener;
}
}
public interface ListListener<T> {
/* .. */
void beforeAdd(T item);
void afterAdd(T item);
/* .. */
}
public interface Listenable<T> {
/* .. */
void setListener(ListListener<T> listener);
/* .. */
}
The reason I'd do it this way would be to allow for creating truly ad-hoc listeners on the fly instead of tying the ListenableArrayList to some specific implementation. For example with this the following would be possible:
Listenable<String> list = new ListenableArrayList<String>();
list.setListener(new ListListener<String>() {
#Override
public void beforeAdd(String item) {
System.out.println("About to add element "+item+"...");
}
#Override
public void afterAdd(String item) {
System.out.println("...element "+item+" has been added.");
}
});
A bit cluttered, maybe but on the other hand this would allow for easy extension to Collections, Sets and whatnot rather easily.
Take a look at Glazed Lists library, which has support for observable collections.
If I were to do it myself, I would likely create custom Listener interface with elementsAdded, elementsRemoved methods, or similar :-) (also depending on my needs)
You can use an Observable Collection: https://commons.apache.org/dormant/events/apidocs/org/apache/commons/events/observable/ObservableCollection.html
Normally I'd do the following:
public class MyBean {
private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private List<String> names = new ArrayList<String>();
public void addName(String name) {
names.add(name);
pcs.firePropertyChange("names", null, Collections.unmodifiableList(names));
}
public void addPropertyChangeListener(PropertyChangeListener l) {
pcs.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
pcs.removePropertyChangeListener(l);
}
}
PropertyChangeSupport manages the listeners and fires the events on your behalf.
By passing null as the "old value" it forces the event to be fired. (It's likely that listeners won't really care about the old value anyway)
JDK 7+ solution:
import javafx.collections.*;
import java.util.*;
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("s1");
list.add("s2");
ObservableList<String> observableList = FXCollections.observableList(list);
observableList.addListener(new ListChangeListener<String>() {
#Override
public void onChanged(Change<? extends String> change) {
while(change.next()){
System.out.println("added: " + change.getAddedSubList());
}
}
});
observableList.add("s3");
}
}
For a swing GUI event I'd normally just use an EventListenerList to do the work for me.
EDIT: on the rephrase of the questions: how do you treat collections, I'd usually use an event similar to the collections type, so for example a TreeModel event usually takes a TreePath argument, or for something in a map I'd indicate the key.
However for simple JavaBeans the most common is assume a list/array and just use the index.
Methinks you will need fireNamesPropertyAdd, fireNamesProperyDelete. A list level notification will IMHO not work, even if it was an array and an index was added as it can't handle deletes. If the element at some index can be changed, you will also need fireNamesProperyChange. It might be useful to have index as parameter in addition to the string value.
Are you perhaps looking for java.beans.PropertyChangeSupport?
In my opinion, you should avoid PropertyChangeEvent. IndexedPropertyChangeEvent is worse, and very infrequently used by Swing anyway. It's better to narrow the focus of your types, and fire a javax.swing.event.ChangeEvent or similar (even just call a Runnable).
For certain types (like lists!), Glazed Lists (or equivalent) mentioned in another post by Peter Štibraný seem like a good way to go.

Categories