List instead of Array in varargs java method [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a varargs method in java. So, the method expects an array of Objects. I passed a List to the method and it worked! I mean, it not only compiled, but the tests were green. So, my question is - do I have to call myList.toArray() when calling the method, or does this call happen automatically?
Thanks in advance!
And here is the code:
createSomething(final Object... parameters) {
// varargs method
}
List<Object> data = new ArrayList<Object>();
createSomething(data); // is this wrong?
createSomething(data.toArray()); // should I always do this?

You seem to think that the list was implicitely transformed to an array, and that the method was invoked with an array containing each element of the list.
That's not the case. In fact, the method was invoked with an array containing a single element: the list itself.
Test it with
private void testVarargs(Object... args) {
System.out.println(args.length);
System.out.println(args[0]);
}
and
List<String> list = Arrays.asList("hello", "world");
testVarargs(list);
The result won't be
2
hello
but
1
[hello, world]
And that's normal: you just passed a single object as argument to the method, which happens to be a List. The List is thus enclosed inside a one-length array and the method is called with that array as argument.

Related

Checking size of stack (ArrayList) in Java? [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 8 years ago.
Improve this question
I'm trying to implement a stack with an Array List.
BlueJ tells me that "size" has private access in java.util.ArrayList even though the Array List is public, when I'm compiling.
int stackLength = stackStorage.size;
System.out.println(+stackLength);
And if I change the line to..
int stackLength = stackStorage.size();
the program compiles and I get a nullPointerExcetion when I run the function.
I don't understand why this is happening because a value cannot be manually assigned because the value needs to come from the stack size.
Any help appreciated, cheers.
You can't directly call for the variable (because it's a private field). You should use stackStorage.size() instead. Also make sure stackStorage is actually instantiated.
You most probably have:
ArrayList<Object> stackStorage;
However you must instantiate it somewhere like so:
stackStorage = new ArrayList<Object>();
This may also be done on the same line:
ArrayList<Object> stackStorage = new ArrayList<Object>();
Once you have created this ArrayList do note that it still doesn't have any elements in it. In order to actually add an Integer to the array simply do:
stackStorage.add(number);
And after you do that, if you call stackStorage.size() it should return 1, meaning there's one element in the ArrayList. If you wish to add more, simply use the add() method. Also make sure you add the same object as you instantiated it with. You can't store String in ArrayList<Integer> for example.
Full-code example:
ArrayList<Integer> stackStorage = new ArrayList<Integer>();
stackStorage.add(10); //Now has value `10` in `index[0]`
System.out.println("index[0]: " + stackStorage.get(0)); //Prints 10
System.out.println("stackStorage.size() = " + stackStorage.size()) //Prints 1
In your case replace Object with Integer if you wish to store integers. NullPointerException means your object is still null when you tried to call size(). This should solve your issue. If you're not sure what null is or don't quite understand what NPE(NullPointException) is I suggest reading about it and if you have further difficulties, posting it here.
That's because size is a private field and hence you don't have access to it, where size() is a public method that you can use. Therefore call size() to get the size of the ArrayList. The NullPointerException has nothing to do with size it is simple because your object is not initialized, make sure you initialize your objects before using them.
List<Something> list = new ArrayList<Something>();
size is a private variable
size() is a public method
For getting the size of the arrayList , you need to use size() and before calling size() dont forgot to intialize the array List like below .
List list = new ArrayList();

Java list default implementation? [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 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

Java interface and extending ArrayList [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to understand Java and I found this code in a text book:
public EArrayList filt(Func a)
{
}
where apply is in an interface called Func
I understood that this method applies a function filter on a list and returns a new list filtered. However I can't understand why Object elem is used. I tried the code and it won't work if I rename Object.
Also I can't understand the following line:
if((Boolean)a.apply(elem) == true)
(what does Boolean stand for apart from return type)
Can someone send me a good link to understand better how this works since I searched a lot about interfaces and never came across this format.
...However I can't understand why Object elem is used.
The likelihood is that EArrayList extends ArrayList, but doesn't give it a type bound - hence, it can hold any object.
Typically, you find Lists with some type bound, such as List<String>, or List<Integer>. If you omit that, then you are dealing with only Objects.
You're also doing it again with Func a - it has a type bound of <S, T>, which one could presume that you're going from a type of S to a type of T. But that is omitted as well, so you're only dealing with Func<Object, Object>.
That's where this cast comes from:
(Boolean)a.apply(elem)
You can omit the == true part. You're checking boolean values.
Java only knows that it is returning an Object from apply, but you don't want an Object - you want a Boolean. Java will attempt to cast it to a Boolean for you, if it can be cast to one. That could blow up at runtime, which means that this particular piece of code is a bug waiting to have a AbstractObjectFactoryImpl inserted into the list, waiting to try to be cast to a Boolean.
This is why you want to use Generics. They protect you from runtime failures like that by enforcing this stuff at compile time, virtually eliminating type casts.
Had this been done with generics, you would see declarations like this:
// Assuming that there is a generic type T on the class:
public EArrayList<T> filter(Func<Boolean, T> a) {
int size = size();
EArrayList<T> arr = new EArrayList<T>();
for(int i = 0; i < size; i++) {
T elem = get(i);
if(a.apply(elem)) {
arr.add(elem);
}
}
return arr;
}

Object update inside ArrayList [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can I get the second object from an arrayList of type (class)Person and apply a method to that particular object?
ArrayList<Person> person = new ArrayList<Person>();
For ex. I have a method in Person class called hasBirthday() which add one year to the object person but it applies only to the second Object created. This in order to display a message of happy birthday and add one year once the second object is created from the console. After all we like birthdays ;)
I believe you mean this:
person.get(1).hasBirthday();
that will call hasBirthday method on the second object in the list (if it exists).
Here's a safe way to do that:
if(person.size() >1 && person.get(1) != null){
person.get(1).hasBirthday();
}
This checks the List is of proper length, and the value at that index is not null.
I'd rename your hasBirthday method to something like increaseAge, or a setter to assign age, like setAge if age is something you allow to be assigned. Descriptive method names are useful.
ArrayList<Person> person = new ArrayList<Person>();
person.add(new Person(someParam1));
person.add(new Person(someParam2));
person.add(new Person(someParam3));
if (person.size() >= 2) {
Person secondPerson = person.get(1);
secondPerson.hasBirthday();
}

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