Object update inside ArrayList [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
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();
}

Related

how to update an element from specific index in ArrayList [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 2 years ago.
Improve this question
How to update an element from an Arrayist that consists of another ArrayList?
I have a class named Product that consist of name, type, currentQuantity, purchaseQuantity. I have created an ArrayList called productList to store each product's data that has been added into into Product class.
My problem is when I go to another class and I want to update the toPurchase element of a specific product of index i, I am now confused on how to do so.
I have declared this in the class:
private ArrayList<Product> productList;
And I tried doing this:
productList.set(productIndex, product.setPurchaseQuantity(pPurchaseQuantity));
But there's a red line underneath product.setPurchaseQuantity(pPurchaseQuantity) that mentioned this:
Required type: Product
Provided: void
So far that those are the only code in my new class.
The type mismatch happens because product.setPurchaseQuantity(pPurchaseQuantity) returns void but productList.set(...) requires an object of type Product as its second argument.
To update the quantity, you need to get a Product from the productList and then operate on the retrieved object. There is no need to set this object again since you are changing an attribute of this object and the reference to it remains in the productList.
Product product = productList.get(productIndex);
product.setPurchaseQuantity(pPurchaseQuantity);
You basically are not changing any thing in arrayList, what you want to do is to update an object which is already referenced in this arrayList, to do so you can just get this object and update (see below)
productList.get(productIndex).setPurchaseQuantity(pPurchaseQuantity)

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

List instead of Array in varargs java method [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 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.

How can i sort the array of objects[contains details like name,address] based on the Alphabetical order in java? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to enter the details of multiple persons and storing them in different objects.
And i have created an array for that objects, now i need to sort them according to the alphabetical order of their names.
Do some thing like
Arrays.sort( array, new Comparator<YourObject>(){
#Override
public int compare(YourObject o1, YourObject o2){
return o1.getName().compareTo(o2.getName());
}
});
I've written a framework to sort natural language text representations of objects in locale-sensitive order:
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/text/Localizables.html
Either your "person class" would need to implement Localizable or you would have to provide a PersonLocalizer by extending Localizer.
Maven:
<dependency>
<groupId>org.softsmithy.lib</groupId>
<artifactId>softsmithy-lib-core</artifactId>
<version>0.3</version>
</dependency>
Download:
http://sourceforge.net/projects/softsmithy/files/softsmithy/v0.3/
implement Comparable<> interface in your class and override compareTo() method in Person class. the method takes Object class as a passed value. For example,
public class Person implements Comparable<Person> {
//omitted
public int compareTo(Person other) {
return name.compareTo(other.name);
} }
check out the following link to learn more http://download.oracle.com/javase/tutorial/collections/interfaces/order.html

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