I am trying to access a variable that is stores as part of an object that is in an array. However that array is in an arraylist. How can access that variable?
To make it clear, I have a car object that has speed. I placed 4 cars in an array. And that array is duplicated and put in an arraylist.
public int getSpeedOfCarA (int index) {//used to access the variable speed in an array
return garage [index].getSpeed ();
}
Now I was trying this but got stuck.
public int getSpeedOfCarB(int n){
carSpeeds.get(...); //not sure what to use here.
}
To access things inside of other things, simply chain the access syntax together. For the example of getting a field inside an object inside an array inside a List, you would simply use
list.get(pos)[arrayPos].fieldName
You may be misunderstanding how ArrayList works however: When working with it, you never see the array, and in fact as far as syntax is concerned it doesn't matter whether it's implemented as an Array or as a LinkedList or whatever else. If so, you need not use any array operator, as the get method will do that for you:
list.get(pos).fieldName
I prefer to use an Iterator to access the car object in the list.
ArrayList<Car> list = new ArrayList<Car>();
Iterator i = list.iterator();
while(i.hasNext()){
Car car = i.next();
}
Use,
for(Car[] carArrays : listOfCarArrays) {
for (Car car : carArrays) {
//do something with car like car.getSpeed();
}
}
Related
I still can't understand when and why should I use the "Obj obj = new Obj" and I don't get why it's so difficult for me.
In this assignment I need to create a method as it follows:
"insertSorted: This method assumes the input LinkedList is already sorted in non-descending order (i.e.,such that each element is greater than or equal to the one that is before it, and inserts the input int value into the correct location of the list. Note that the method does not return anything, but rather modifies the input LinkedList as a side effect. If the input LinkedList is null, this method should simply terminate. This is the code you're starting with:
public static void insertSorted(LinkedList<Integer> list, int value) {
/* IMPLEMENT THIS METHOD! */
}
Let alone all the complications about iterating the LinkedList list, I don't even know how to start.
Should I create a new LinkedList<Integer> newList = new LinkedList<Integer>(); so I can iterate through it right? Why though? If the list is given in the method signature should I assume that the Object is already created when the input is given in the method signature?
I am really confused. It seems that I can't quite catch the whole Object programming thing.
Obj obj = new Obj
well if want to understand the new keyword in one line its like a contract in memory area where you can store the data (thats not all but enough to start).
public static void insertSorted(LinkedList<Integer> list, int value) {
/* IMPLEMENT THIS METHOD! */
}
Now for this method you donot want to create any new object.
Q.Why?
Ans- when this method will called their is mandatory to pass some parameter to the method if not it will be a compile time error.
Passing values could be null.
Since the method returns void you should modify the list that is given as input.
I'll show you why with an example
public static void insertSorted(LinkedList<Integer> list, int value) {
LinkedList<Integer> list2 = new LinkedList<Integer>(list); //this means you are creating a new list of integers called list 2 with the same elements of the list "list" in the same order
//some code to add value to list2 maintaing the sorting
//no return needed
}
somewhere else you want to call this method
LinkedList<Integer> list = new LinkedList<Integer>();
list.Add(1);
list.Add(2);
list.Add(5);
for (Integer i : list) System.out.println(i);
//prints 1, 2 , 5
insertSorted(list,4);
for (Integer i : list) System.out.println(i);
//still prints 1, 2 , 5!
if now you run this code with a debugger and you break in the method insertSorted right after you inserted the value in list2 you will see that list "list" remains as it was at the start of the method (which is (1,2,5)) and the list "list2" will be (1,2,4,5).
But the caller method knows nothing about list2!!!
When you declare a variable within a method it dies when the method ends (unless you return it). Of course you should pay attention to the "aliasing", but this is not the case.
Your requirements are very clear: your method must modify the input rather than creating a new list.
You can't understand why you should create a new object just because you don't have to. Someone just gave you a wrong suggestion :)
Now it's up to you to iterate the list and insert the integer in the right place :)
This is an assignment, I can't post the entire code, but I really need understand what I'm doing wrong. I'm sure its a rookie mistake.:(
I had to construct a custom sort method,that sorts specific properties of my arraylist objects. I've created different Comparators to address the different elements within the objects I want sorted.
*edit added more code
sort utility method (parameters required):
public class CarManage{
private ArrayList <Car> carList; //carList defined
public class Sorts {
public static void sorts(Car[]carList, int size, Comparator <Car> someComparator) //given parameters not allowed to modify
{
//sorts arrayList(carList) objects using an insertion sort algorithm.
}
}
} //end class
I try call the sort method, to specify which properties I need sort, but alas it rejects the first parameters.
public void sortByVinNumber(){
VinNumComparator vnc = new VinNumComparator();//one of many comparators
Sorts vncSort = new Sorts();
for(int i = 0; i < carList.size(); i++){
if(vnc.compare(carList.get(i-1), carList.get(i)) > 0){
vncSort.sorts(Car[]carList, 2, vnc);//not working here rejects first parameter
///vncSort.sorts(carList,2,vnc)///doesn't work
}
}
}
I'm not sure why it won't accept my parameter? Could it be a pass-reference mistake? Or am I possibly calling the method wrong?
You need to call the method like so:
vncSort.sorts(carList, 2, vnc);
Also, it seems like you're confusing an array with an ArrayList. An Array of Car would be Car[]. An ArrayList<Car> is a List which accepts and produces Car types. The reason it's called ArrayList is because it's backed internally by an array.
I have an array which contains values pawnArray. I need to find the highest value in pawnArray so using a custom class method getPawn() I retrieve the highest value but I do
public static Pawn getPawn(Array<Pawn> strollpawns) {
Array<Pawn> pawns = strollpawns;
pawns.sort();
Pawn best = pawns.get(0);
return best;
}
I hence need to copy the array since this method doesn't work. How can I make a copy of this array?
If your problem is with Java arrays (the syntax is Pawn[]) then you have methods in class java.util.Arrays for many different operations on them. What you are asking for could be accomplished with:
Pawn[] newArr = Arrays.copyOf(oldArr, oldArr.length);
Or, since array classes implement Cloneable, also with:
Pawn[] newArr = (Pawn[]) oldArr.clone(); // I don't remember if the cast is necessary
Note that both of these provide shallow copies, that is, the arrays are independent of each other (you can sort one and the indexes in the other are unaffected) but their contents are not.
EDIT: it has been kindly pointed out to me that your Array<T> is actually a class in libgdx. Looking at the documentation, then, you could simply use the constructor taking another instance of Array to create your shallow copy, since the doc says that the new instance will have the same type of backing array (not the same instance). For example:
Array<T> newArr = new Array<>(oldArr); // oldArr can be either Array<? extends T> or T[]
I'm adding a separate answer to this, since you want to copy your array and sort it in order to retrieve the highest value. My other answer deals with copying the array, while tjago's answer deals with sorting with a custom Comparator in order to customize what the "max value" is. However, it seems that the libgdx Array<T> class has a method to do just what you want, without having to make a sorted copy of the array.
This solution saves you code, memory and time if you only need one value from the sorted array: the minimum, maximum, whatever. If you need more than one, it is likely that sorting the array will be faster.
The method I'm talking about is Array.selectRanked, which returns the nth element according to the provided Comparator. There is another method selectRankedIndex which returns the index of that element instead of the object itself. You could use it like this:
// If Pawn implements Comparable<Pawn>:
Pawn minVal = arr.selectRanked(Comparator.naturalOrder(), 1);
Pawn maxVal = arr.selectRanked(Comparator.naturalOrder(), arr.size);
// If it does not implement Comparable, you need to provide a Comparator<Pawn>:
// Assuming Pawn has an "int getValue()" method that we want to compare:
Pawn minVal = arr.selectRanked(Comparator.comparingInt(Pawn::getValue), 1);
// You could also write your own implementation directly:
Comparator<Pawn> comp = (a,b) -> /* your int-returning logic here */;
Pawn minVal = arr.selectRanked(comp, 1);
It seems you have a java related problem. To help you with sorting In java object programming there exist concept of method overriding and interfaces.
Special interface for sorting is Comparator, you can either put him inline in method like this.
Collections.sort(pawns ,new Comparator<Student>(){
public int compare(Pawn1 p1,Pawn2 p2){
// Write your logic here.
//ie.:
return p1.score - p2.score;
//or for different order
return p2.score - p1.score;
}});
if this comparator return value == 0 means the value are equal;
if value < 0 means p1 is bigger than p2, therefore swap them.
Or put him inside your Object class like:
Class Pawn implements Comparator {
private String name;
private Position[][] posXY;
private int value;
....
Pawn() { ... }
...
public int compare(Pawn1 p1,Pawn2 p2){
return p1.value- p2.value;
}
}
then in your code you can call as you originally intended:
pawns.sort();
Pawn best = pawns.get(0);
and as expected you should get an maximum value Pawn from ArrayList.
The above code is just sample and requires tunning. But You should get an good overview now that Java has no idea how to sort Objects defined by a programmer unless he implements the Comparator logic for Collection sorting.
for external reference I suggest running a simple example on tutorialpoint
Answer to your question: How can I create copy of a libgdx array
Array<Pawn> pawns = new Array<Pawn>(strollpawns);
or if the pawns Array object already exists
pawns.clear();
pawns.addAll(strollpawns);
The first solution will create a new Array object that will be deleted on completion of the function, meaning time lost by garbage collector!
But I agree with Tenfour04: Duplicating an array and sorting it is a very expensive way to select the biggest value.
i know how to hard code an algorithm on how to check the types of each object in an arraylist, but is there any other way in checking the type of that ArrayList<> in one go, i mean my application has only three types of arraylist. Say i have a function that returns an ArrayList, and its definiton is that in a variable o (its an arraylist of object ofcourse) i'll add a person object,
o.add(person);
and having added all person data on an arraylist of objects and when a call this function say the name of my function is getData(),
ArrayList <Object> obj = getData();
so i know that in that ArrayList that i returned from calling getData() that it is all person object, how do i know the type of that ArrayList?.
Just wanted that function to be more generic in sense, this is for my application though, geniric troughout my application.
Is there any other way of doing this, i can think of an algorithm but is there any short cut or easy way of doing this?..
There is no such thing as 'the type' of an ArrayList.
The class ArrayList stores a list of Object references. It doesn't know and doesn't care if they are all of some type.
The Java generic system adds compile-time checking to help you keep track of types. So, if you declare ArrayList<Person>, you will get compile errors if you write code that could insert a non-Person into your list.
At runtime, the only way to tell what is in an ArrayList to iterate over all the contained items and check them with instanceof.
Actually there is a way without casting every item manually(it still is ugly though..)
//start with an arraylist of unknown generic type
ArrayList <Object> obj = getData();
//Make an array from it(basically the same as looping over the list
// and casting it to the real type of the list entries)
Object[] objArr = obj.toArray();
//Check if the array is not empty and if the componentType of the
//array can hold an instance of the class Person
if(objArr.length>0
&& objArr.getClass().getComponentType().isAssignableFrom(Person.class)) {
// do sth....
}
This should not give any unchecked warnings.
You could use it like this:
private boolean isArrayOfType(Object[] array,Class<?> aClass) {
return array.length > 0
&& array.getClass().getComponentType().isAssignableFrom(aClass);
}
Object[] personArr = getData().toArray();
if(isArrayOfType(personArr,Person.class) {
//Do anything...
}
What won't work is the following:
// -> This won't work, sry!
ArrayList<Person> personArrayList = Arrays.asList((Person[])personArr);
If the list is not empty, get the first element:
type = this.list.get(0).getClass().getSimpleName();
I had two classes: ParentClass and SubClass. SubClass inherit from ParentClass.
I had the following code: (inside class)
List<SubClass> lstSub;
//some initialization
public ListIterator getLstIterator(int i) {
return lstSub.listIterator(i);
}
And client class uses it the following way:
ListIterator<ParentClass> lstParent = getLstIterator(0); //assign ListIterators
So, the question:
What does the program do while assigning ListIterators:
1) it creates a new list and copies there elements from source list, casting them to ParentClass;
2) it simply creates a link to lstSub and from this time this list is interpreted as List for ListIterator?
Or it does something else?
I'm interested in it because of program performance. I'm new to Java and appreciate any help.
It doesn't create another list. If you get a list iterator without knowing the class in the list, that's going to be an error in your generics usage. You should get a warning when you do that assignment, but it's just a warning. When you actually use it it'll cast to whatever class. Properly you'd hold on to that as ListIterator<? extends ParentClass> if you wanted a list iterator, but actually holding on to an iterator is a little weird.
Finally, just a bit of advice, I'd not worry about performance of the language features too much, especially if you're just getting your feet in the language.
A new instance of ListIterator is created. The reference to the new object is copied into lstParent
See here
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
Disclaimer: This example is specific to ArrayList.
Performance-wise, there's no list copying going on.
But to have the compiler check the type-safety of the code, you should declare the type parameters like this:
public ListIterator<SubClass> getLstIterator(int i) {
return lstSub.listIterator(i);
}
...
ListIterator<? extends ParentClass> lstParent = getLstIterator(0);