This question already has answers here:
compareTo Error: Cannot invoke compareTo(int) on the primitive type int
(2 answers)
Closed 2 years ago.
So I am looking to sort an array list of objects based on a field in the object but I am getting an error "Cannot resolve method compareTo(int)"
ArrayList<SuperHero> herolistClone = (ArrayList<SuperHero>) superheroList.clone();
Collections.sort(herolistClone, new Comparator<SuperHero>() {
#Override
public int compare(SuperHero superHero, SuperHero superHeroTwo) {
return superHero.getCiviliansSaved().compareTo(superHeroTwo.getCiviliansSaved());
}
});
}
I assume getCiviliansSaved() returns an int? ints are not objects, thus, cannot be dereferenced (the 'dot' operator cannot be applied to them).
Try Integer.compare(superHero.getCiviliansSaved(), superHeroTwo.getCiviliansSaved());
Or, replace all of it with modern, shiny new java:
heroListClone.sort(Comparator.comparingInt(SuperHero::getCiviliansSaved));
boom, more readable, and turned 5 complicated lines into a single one.
I'm predicting you want to reverse the sort (list the hero that saved the most, at the 0 position in your list), in which case, just slap a .reversed() at the end there, right before the last );.
Related
This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 4 years ago.
Ok so I need to make an object, modify its values using a Java scanner method, add it to a list, and do this 3 times so I have 3 objects in the list all with different values. I then need to use a for loop to print each object.
Here is my code so far. However every time the for loop outputs to to console, it prints 3 objects.. but their values are all the same (that of the final modification) For the sake of simplicity I won't add my class or method codes unless requested. So stuck on this!!
ArrayList<Car>carList = new ArrayList<Car>();
Car b = new Car(0, 0, 0, 0);
modifyCar(b);
carList.add(b);
modifyCar(b);
carList.add(b);
modifyCar(b);
carList.add(b);
for(Car x: carList)
{
x.print();
}
You're creating a single instance of Car, and then storing a REFERENCE to it in the List.
You then modify the instance, and store another reference to the SAME Car.
In the end, you'll end up with a list containing 3 references to the same Car, which will have the result of whatever modifyCar() does.
Create a new Car before calling modifyCar each time.
This question already has answers here:
What happens if two different objects have the same hashcode?
(5 answers)
Closed 4 years ago.
I have a Hashtable to find objects by number. Let's assume I do
Hashtable<Integer, MyClass> table = ...
table.put(10, myObject);
and query this with a byte or Byte object that also has value 10, then I get no result.
Byte b = new Byte(10);
table.get(b); // -> null
table.get((int)b); // -> myObject
table.get(10); // -> myObject
table.get((byte)10); // -> null
Byte and Integer objects are different, I know. But it compiles and both have the same hashcode, namely the value 10. Shouldn't both find the object?
The byte value on one of my cases is unchangeable. I can cast it to int but I would like to understand what's going on here.
Edit: Let me make clearer what my problem was. I thought as this hashlist has an Integer as key type, either I should get an error if I use something different that an int (which is converted into integer) or another number type is automatically converted into int. This made me wonder.
It is not enough they got same hashCode, when you call get method, the key should also equals the one you put before.
Byte and Integer are different classes, so they are not equal with each other, that's why you got null with table.get(b) or table.get((byte)10).
This question already has answers here:
How do I determine whether an array contains a particular value in Java?
(30 answers)
Closed 6 years ago.
I have a similar logic for a method in a Java Class (not the real code, this is simplified for example purposes).
private Boolean method(Boolean booleanValue, SomeObject object) {
return booleanValue ? Arrays.asList(object.getStringsArray()).contains("string") : false;
}
A collaborator who assigned himself to check the PR gave the following comment:
This is inefficient. It is creating a new data structure only to iterate it and check if there is a certain string.
The getStringsArray() method returns a String[], so will using a for-loop be better than Arrays.asList()?
Which way is more efficient to achieve this?
Your co-worker is incorrect when they assert that your method is creating a new data structure.
If you look at the API for Arrays.asList(), it says that it
Returns a fixed-size list backed by the specified array.
There is no reason to write your own code to iterate over the array when you can just wrap a List around it, and use its built-in methods.
This question already has answers here:
What does <T> (angle brackets) mean in Java?
(6 answers)
Closed 8 years ago.
So, while looking through others code ive been seeing things like such as in the following code:
List myList = new ArrayList<String>(Arrays.asList(s.split(" ")));
What exactly does this do? I haven't been able to find any documentation, in part by the reason that I don't really know what it is called. And if possible an explanation of what exactly they do?
That particular code generates a list that contains the entries resulted from splitting the s string at each space.
The < String> defines the generic type for the List, and the advantage (among other ones) is that you can call myList.get(index) and not have to cast it to a String.
This is a generic. You are instantiating an ArrayList that stores String objects.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In Java, how can I test if an Array contains a certain value?
I have an array setup as follows:
Material[] blockedlevel1 = {
Material.mymaterialone, Material.mymaterialtwo
};
How do I see if a Material is in this array?
How about looking for it in the array?
for (Material m : blockedlevel1) {
if (m.equals(searchedMaterial)) { // assuming that equals() was overriden
// found it! do something with it
break;
}
}
If you want an easy way to check if an element is part of a collection you should probably consider a different data-structure like Set (and use contains()). With Array you can only iterate over the elements and compare each one.
How about looking for it using the Arrays class?
See Arrays#binarySearch
Or as someone suggested, turn your array into a List and use the contains() method. Remember that you may have to override the Material#equals method.