Java list default implementation? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
If I declare a new list like this:
List<String> listExample = someFunction();
what list interface implementation will be used?
EDIT: Thanks for the answers so far. What is considered as the clean way to do this, should I always declare list with new?

As Eran commented that totally depends on what someFunction(); returns .Both ArrayList<E> and LinkedList implements List interface .
You can try ,
System.out.println("" + listExample.getClass());
to find out the which has been implemented. From docs,
public final Class<?> getClass()
Returns the runtime class of this Object. The returned Class object is
the object that is locked by static synchronized methods of the
represented class.

Whatever you are building e.g. LinkedList, ArrayList, Vector, Stack in and returning from someFunction() will be implemented with listexample. If you are using List interface reference, it has one benefit, that you can assign any type of object to it (LinkedList, ArrayList, Vector, Stack).

eg if u give
List listExample = new ArrayList();
Then the Object will be created for ArrayList and list is just an instance of listExample.
and you can use getClass() for that listExample to view

Related

Telling ArrayList to .add() Itself in Java [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 1 year ago.
Improve this question
I came across this code. I was wondering if this is possible. As you can see, aList is an ArrayList which .adds() itself.
ArrayList<Object> aList;
aList = new ArrayList<Object>();
aList.add("cat");
aList.add(aList);
aList.add(12);
int size = 0;
Iterator<Object> it = aList.iterator();
while(it.hasNext()) {
it.next();
size++;
}
System.out.print(size);
Yes, it is possible. There are no restrictions on the elements you can add to a ArrayList<Object>.
And you can iterate the list, and do various other things with it.
But don't call toString() on it because you might get a StackOverflowError.
UPDATE - For (at least) Oracle / OpenJDK Java 6 and onwards, the toString() method inherited from AbstractCollection will detect this "self reference" cycle and show it as (this collection) rather than going into an infinite recursive loop.
However:
This is an implementation detail. It is not part of the specification.
I don't know if this applies for all Java versions; i.e. prior to Java 6, and Android versions.
This doesn't apply for 3rd-party List classes that don't extend AbstractCollection. (For them, you would need to check the implementation code to understand what would happen.)
It doesn't apply if the self-reference cycle has more than one "hop"; e.g. list A contains list B, and list B contains list A. In such cases you would get infinite recursion and a StackOverflowError.
So caution is advised.

Why Collection dont have and getAll method? [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 3 years ago.
Improve this question
I may I not search enought but I haven't find any answer.
[[Collection]<T>][1] have an T get() methode, an void add(T t) method, and an void addAll(Collection<? extends T> c) method.
Then why we dont have an Collection<? extends T> getAll(Predicate<? extends T> p) method?
I know taht it souldn't be hard to make a subclass who implements it. But I dont understand why it is not already their.
Late edit:
Here a concrete exemple for sceptical.
I have to code :
wellsDisplayers = new ArrayList<DisplayWell>(Arrays.asList(displayerList.stream().filter(x->DisplayWell.class.isInstance(x)).toArray(DisplayWell[]::new)));
instead of :
wellsDisplayers = displayerList.getAll(x->DisplayWell.class.isInstance(x));
But you are right stream methode is really easy to use and understand, just like how java sould be.
I think you misunderstood the concept of a Collection. There is no getAll() method since you already have every element. Simply use the stream().filter() syntax and collect or map to do whatever e.g.
collection.stream().filter(x -> x..) // do stuff
I think you're looking for Collection.removeIf(Predicate<? super E> filter), although you'll need to negate the predicate logic. Alternately, you can use streams: collection.stream().filter(p).
As for why there isn't a getAll to go along with the other methods, I don't see where the Predicate parameter is coming from, you're not getting "all" if you filter some out. The addAll method adds all the elements, so the analagous method getAll would get all the elements, which is just the collection itself, so it would be redundant.
Also, Collection doesn't even have a get() method in the first place. Maybe you're thinking of List.get(int). I suppose you could have an "All" version like getAll(int[]) that returns the elements at all the given indexes, but that doesn't seem very useful when subList(int, int) already exists.

Editing in a copy arraylist from original one [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Now, I have encountered this problem:
I have a non-empty array list declared as original. Then I do this :
ArrayList<ArrayList<Integer>> temp = (ArrayList<ArrayList<Integer>>) original.clone();
temp.get(0).set(1,-1) ;
but the result was that unexpectedly the element at index 1 in both lists were changed.
How can I fix this problem ?
clone makes a shallow copy of the ArrayList. Either make it's Deep Copy since the ArrayList is object type so it can also make new object of it's reference.
You have to deep copy, you can try below code
for(int element:original)
{
temp.add(element);
}
clone makes a shallow copy of the ArrayList. In a sense, this means affecting the ArrayList from one reference also affects the other reference.
Instead, use new ArrayList(original).
Edit: My mistake. You'd have to go through the contents of your ArrayList and clone each object inside. Unfortunately for you, you have ArrayLists inside your ArrayList, so you'd have to do a lot of iterating if you want distinct Integers.

JAVA variable as 2 types [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 8 years ago.
Improve this question
How can I create value of type String and also Collection?
I want someTimes put in this Strings and the othertimes put collections.
for example in javascript I would do
var k;
if (someBoolean){
k=1;
} else{
k=[1,2,3];
}
can I get this behavior of the variable in java, hack or something?
I found Solution: I created an interface and declear this Objects as this interface.
Java does not support union types; however, both of these types share the same base Object class, so you could assign either one of them to a variable defined like this
Object something;
something = "Hello World!";
something = new ArrayList(); // this is a collection.
Odds are that you probably were thinking of a Collection of Strings, in which case, you define it like Collection<String>
Collection<String> strings = new ArrayList<String>();
strings.add("Hello");
strings.add("World");
strings.add("!");
If that's not what you wanted, and you really want to sometimes store a String and sometimes store a Collection, remember that Java enforces strict type checking. This means that variables cannot just store anything, they must store something that is type compatible.
String and Collection are too different to be considered type compatible without some seriously bad programming (like using Object) or something even stranger.
You cant. String is a final class, meaning you cannot extend upon it. A String will only ever be a String. You can have a collections that contain Strings, but a String object will only have 2 types: Object and String.
You can have a class that contains a String (or a StringBuilder) and a collection, then use that class to store/receive from

Why those methods which are used has just one parameter although methods require values of two elements? [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 8 years ago.
Improve this question
Class Alkio of my previous! question is chosen to do more methods.
Implement to the class in addition to the previous ones following
methods:
public boolean suurempiArvo(Alkio verrattava)
and
public int compareTo(Alkio verrattava)
Method suurempiArvo returns true, if the value of the object is
greater than value of verrattava. Method compareTo compares the
values of elements and returns an integer( negative, if the value of
the object is less that value of verrattava, zero, is values are the
same and otherwise positive)
Questions.
Why those methods which are used has just one parameter although methods require values of two elements? If I refer in the methods to verrattava by writing verrattava, how do I refer to object?
When you have a method
public int compareTo(SomeObject other) {
// needs implementation
}
You are comparing other with the current instance. That is to say, the reason why you do not need the second element in the signature is that the second element is already there, it's the object whose method is being invoked. You compare the members of other with the members of the present instance, basically this, in order to arrive at the proper result.
public int compareTo(SomeObject other) {
// assumes member variable foo
if (this.foo > other.foo) {
// you finish implementation
}
}
For clarification, if you were to invoke these methods, it would be something like
SomeObject first = new SomeObject();
SomeObject second = new SomeObject();
int result = first.compareTo(second);
So you pass the second object into the compareTo method of first. first then compares itself against the second (this vs. other).
Object would appear to refer to the instance of the Alkio class that you're calling the method on, so you'd refer to it using this.
You should refer to a tutorial on Java classes - and also the compareTo method of Comparable interface. The simple answer to your question is that you are dealing with two objects: verrattava' and the object itself, referrd to withthis, e.g.this.value1`.
Take a look at this article - it's not very well formatted, but does give you the idea - scroll down to an example at the bottom.

Categories