Comparing variables of objects in an array? - java

I've an array of objects in Java. Say these objects Obj contain a variable var, and I have several Obj stored in an array Array[].
I'd like to compare the var between two adjacent Obj but I don't know how, nor can I find any info online (which makes me think i'm working my question wrong or it's not doable or something)
Edit:
I'm currently attempting the rather roundabout method of assigning the array objects in question to new temporary objects and just doing the comparison with those:
Obj o1 = o[i];
Obj o2 = o[i+1];
if (o1.var > o2.var)
//etc
But surely there is something better.

If you have an array of objects, you can do your comparison without creating the temporary references:
MyObject[] arr = //populated somehow
for (int index = 0; index < arr.length - 1; index++) {
if (arr[index].var > arr[index + 1].var) {
//your logic
}
}
You might also want to take a look at the Comparable interface as a means of encapsulating the comparison of the objects based on a particular field. Using this interface would allow you to take advantage of its support in the Collections API.

Based on your edit, it would be fine to say
if (o[i].var > o[i+1].var) { ... }
assuming that o was of type Obj[].
I'm curious, though: are you trying to sort the array? If so, you can use Arrays.sort() (If not, it's a good method to know about anyway.)

I may not be understanding your question correctly, but the following is perfectly valid:
if (o[i].var > o[i+1].var ) { // ...etc... }
Beware of when you hit the end of the array! That is, if you are looping through all of the elements and i is the last one, then o[i+1] will give you an Array Index Out of Bounds error!

Just use them directly without the reference i.e. substitute the array lookup into where you are doing the comparison.
if (o[i].var > o[i+1].var) {
// etc
}
Or in a loop, doing every one programmatically:
for (int i=0; i<o.length-1; i++) {
if (o[i].var > o[i + 1].var) {
// etc
}
}

Related

Need help using java.lang.reflect.Array to sort arrays

An interview question was to write this method to remove duplicate element in an array.
public static Array removeDuplicates(Array a) {
...
return type is java.lang.reflect.Array and parameter is also java.lang.reflect.Array type.
How would this method be called for any array?
Also not sure about my implementation:
public static Array removeDuplicates(Array a)
{
int end=Array.getLength(a)-1;
for(int i=0;i<=end-1;i++)
{
for(int j=i+1;j<=end;j++)
{
if(Array.get(a, i)==Array.get(a, j))
{
Array.set(a, j, Array.get(a, end));
end--;
j--;
}
}
}
Array b=(Array) Array.newInstance(a.getClass(), end+1);
for(int i=0;i<=end;i++)
Array.set(a, i, Array.get(a, i));
return b;
}
You may want to consider using a different data structure such as a hashmap to detect the duplicate (O(1)) instead of looping with nested for loops (O(n^2)). It should give you much better time complexity.
There are various problem with this code. Starting here:
if(Array.get(a, i)==Array.get(a, j))
Keep in mind that those get() calls return Object. So, when you pass in an array of strings, comparing with == simply will most likely result in wrong results (because many objects that are in fact equal still have different references --- so your check returns false all the time!)
So, the first thing to change: use equals() instead of == !
The other problem is:
end--;
Seriously: you never ever change the variable that controls your for loop.
Instead: have another counter, like
int numberOfOutgoingItems = end;
and then decrease that counter!
For your final question - check the javadoc; for example for get(). That reads get(Object array, int index)
So you should be able to do something like:
int a[] = ...;
Object oneValue = Array.get(a, 0);
for example.
Disclaimer. I have to admit: I don't know if the Array implementation is smart enough to automatically turn the elements of an int[] into an Integer object.
It could well be that you have to write code first to detect the exact type of array (if it is an array of int for example); to instead call getInt() instead of getObject().
Beyond that, some further reading how to use reflection/Array can be found here

Sorting an object array into another array based on a variable

I have a problem with a program I'm writing for a school assignment.
Essentially, before this piece of code, I already recieve and work with a bunch of information that I store into an array of objects. Now I have to sort this array (after it's sorted, I will have to calculate some things in the order of the PRIORITY variable).
presume I already have a MyClass[] array called input, that stores a finite amount of MyClass objects.
MyClass[] priorityArray = new MyClass[input.length];
for (int i=0; i<priorityArray.length; i++) {
int maxIndex = 0;
int maxPrivilege = input[i].returnPrivilege();
for (int j=1; j<input.legnth; j++) {
int currentPrivilege = input[j].returnPrivilege();
if (currentPrivilege > maxPrivilege) {
maxPrivilege = currentPrivilege;
maxIndex = j;
}
}
priorityArray[i] = input[maxIndex];
input[maxIndex].setPrivilege(-900000000);
}
the MyClass class if nothing fancy, but of course, contains a proper constructor, getter and setter methods and an integer variable "privilege".
I'm getting an error in my final tests of the program and, seeing as the program returns privileges as "-900000000", it has to have something to do with this part of the code.
It's also not even writing certain MyClass instances from the input array into the priorityArray array.
How can I clead this up? Help.
I'll rewrite my answer totally.
In this line
priorityArray[i] = input[maxIndex];
You are assigning object from one array to another array by reference. It means that there is only one object and you set value to -9000000 in the next line to it. Of course element in priorityArray will have the same changes. To fix it you need to clone your object here.

how can i initialize my array when i cant initialize as null?

i have an array of strings which i want to convert to int, pretty simple and straightforward here is the code :
public static void main(String[] args) {
String myarray[]=readfile("[pathtothefile]");
int mynums[] = new int[myarray.length];
for (int i=0;i<myarray.length;i++){
mynums[i]=Integer.parseInt(myarray[i]);
}
System.out.print(Arrays.toString(mynums));
}
But the Problem here is, if i initialize "mynums" like this: mynums[]=null; i get NullPointerException on the following line:
"mynums[i]=Integer.parseInt(myarray[i]);"
what i have to do to solve it is
int mynums[] = new int[myarray.length];
here someone explained why it happens but i dont know how to initialize now! i mean sometimes i dont know how big my array can get and i just want to initialize it. is it even possible?
In Java everything is a pointer behind the scenes. So when you do mynums[]=null, you are pointing to a null. So what is null[i]? That is where your NPE comes from. Alternatively when you point it to an array, then you are actually accessing the i'th element of the array.
You have to first initialize the array because it allocates memory depending on the array size. When you want to add for example an integer to an array it writes the int into previously allocated memory.
The memory size won't grow bigger as you add more items.( Unless you use Lists or Hashmaps, ... but it's not true for generic arrays)
If you don't know how big your array will be, consider using SparseIntArray. which is like Lists and will grow bigger as you add items.
Briefly, in java an array is an object, thus you need to treat it like an object and initialize it prior to doing anything with it.
Here's an idea. When you're initializing something as null, you're simply declaring that it exists. For example ... if I told you that there is a dog, but I told you nothing about it ... I didn't tell you where it was, how tall it was, how old, male/female, etc ... I told you none of its properties or how to access it, and all I told you was that there IS a dog (whose name is Array, for sake of argument), then that would be all you know. There's a dog whose name is Array and that is it.
Typically, arrays are used when the size is already known and generally the data is meant to be immutable. For data that are meant to be changed, you should use things like ArrayList. These are intended to be changed at will; you can add/remove elements at a whim. For more information about ArrayList, read up on the links posted above.
Now, as for your code:
public static void main(String[] args) {
ArrayList<int> myInts = new ArrayList<int>();
// define a new null arraylist of integers.
// I'm going to assume that readfile() is a way for you get the file
// into myarray. I'm not quite sure why you would need the [], but I'll
// leave it.
String myarray[] = readfile("[pathtothefile]");
for (int i = 0; i < myarray.length; i++) {
//adds the value you've specifed as an integer to the arraylist.
myInts.add(Integer.parseInt(myarray[i]));
}
for (int i = 0; i < myInts.size(); i++) {
//print the integers
System.out.print(Integer.toString(myInts.get(i)));
}
}
What if you don't use an array but an ArrayList? It grows dynamically as you add elements.

How to get an objects string and add this to a string array

I have an ArrayList of my own class Case. The class case provides the method getCaseNumber() I want to add all of the cases casenumber to a String[] caseNumber. I've tried this
public String[] getCaseNumberToTempList(ArrayList<Case> caseList) {
String[] objectCaseNumber = null;
for(int i = 0; i < caseList.size(); i++) {
objectCaseNumber[i] = caseList.get(i).getCaseNumber();
}
return objectCaseNumber;
}
But my compiler complaints about that the objectCaseNumber is null at the point insid the for-loop. How can I manage to complete this?
Well, you need to create an array to start with, and initialize the variable with a reference to the array. (See the Java tutorial for arrays for more information.) For example:
String[] objectCaseNumber = new String[caseList.size()];
Alternatively, build a List<String> (e.g. using ArrayList) instead. That's more flexible - in this case it's simple as you know the size up front, but in other cases being able to just add to a list makes life a lot simpler.
In idiomatic Java, you wouldn't use ArrayList as a parameter type. Use List.
Slightly more overhead, but simpler and more readable code is to accumulate in another List and then convert into an arrray:
public String[] getCaseNumberToTempList(List<Case> caseList) {
final List<String> r = new ArrayList<String>();
for (Case c : caseList) r.add(c.getCaseNumber());
return r.toArray(new Case[0]);
}
In your code it does make sense to insist on ArrayList due to performance implications of random access via get, but if you use this kind of code (and I suggest making a habit of it), then you can work with any List with the same results.
Well, as I think you may have misunderstood Arrays as a primitive type. Arrays in java are objects and they need to be initialized before you access it.

How do I check if an array element exists?

I'm looking for Java's equivalent of PHP's isset();
int board[][]=new int[8][8];
...
if(isset(board[y][x]))
// Do something with board[y][x]
Does such a function exist in Java?
Edit: Sorry, what I meant is that I want to check if board[100][100] exists or not. if(board[100][100]) would result in an array out of bounds error.
In Java, int arrays are initialized to a value of zero, so you won't be able to tell if it's been not set, or if it's set to a value of 0.
If you want to check if it's set, you should use an array of Integer. If the value isn't set, it will be null.
Integer[][] board = new Integer[8][8];
...
if (board[x][y] != null) { ... }
I think a basic null check would work.
String[] myArray = {"Item1", "Item2"};
for(int x =0; x < myArray.length; x++){
if(myArray[0] != null)
{
...do something
}
}
You can create a method that checks that first the x, y is in the bounds of the array and if it is that the value is not null. I don't believe there is a built in method for array, but there are helper functions similar like .contains() for ArrayLists.
Probably better to not use int, you could use Integer if you really have to have it as an int, but generally speaking a complex object is going to be better (like a ChessPiece or something). That way you can check to see if the value == null (null means it has not been set).
if (board[x][y] != null) {
// it's not null, but that doesn't mean it's "set" either. You may want to do further checking to ensure the object or primitive data here is valid
}
Java doesn't have an equiv. to isset because knowing if something is truly set goes beyond just stuffing a value into a location.

Categories