How can I print the second element from the below Object[] args? Is there a way to get it using Arrays.toString(args). I want to get only the 2nd element sayHello
[com.example:type=Hello, sayHello, [Ljava.lang.Object;#1503f191, [Ljava.lang.String;#6229b4c0]
Arrays are objects that can be manipulated by indices too, those indices are integers pointing to its location in the object, furthermore, they are zero based, which means, the 1st element is located at index 0
following the illustration above, what you need is to do Object foo = args[1];
or invoke directly a method if required, e.g. args[1].toString();
Related
I was having some problem when trying to get the first array item out of Optional. Following as my code:
String[] temp = new String[2];
temp[0] = "email1";
temp[1] = "email2";
Optional<String[]> email = Optional.of(temp);
System.out.println(email.map(e -> e.get(0)).orElse(null));
I am trying to get the first email, otherwise just return as null. However, when I run this, I am getting these error messages:
System.out.println(email.map(e -> e.get(0)).orElse(null));
^
symbol: method get(int)
location: variable e of type String[]
1 error
When I tried to do this:
System.out.println(email.stream().findFirst().get());
It prints out weird value:
[Ljava.lang.String;#7adf9f5f
Any ideas? Thanks!
Arrays don't really have methods, per se. .get is something you call on a Collection, not a primitive array. Since the Optional contains an actual, primitive Java array, just use brackets [] to access the element.
System.out.println(email.map(e -> e[0]).orElse(null));
An Optional works alike an if-else test but lay out inside a special object to carry a value and make comparison to an equivalent
You put an "array" as a value into the Optional, the only object get() could return is the array not any of it's elements, also, get() for Optional does not take an argument in it.
The isPresent() boolean and the void
ifPresent(ConsumerAndItsValue cmv) methods are a test to find if the "VALUE" is present, works much more like comparing using if object.equals(this object)
So of you want to use it for particular email addresses you simply put in each string , the tests cannot see into the array, those elements are more objects.
Create a java.util.Consumer≪Anobject> the functional code assigned "to a lambda", Anobject should be the type in accept method accept(T to) method.
Here's a stack overflow page I found
Proper usage of Optional.ifPresent()
And it is possible to iterate over an array contents (external site example). https://mkyong.com/java8/java-8-consumer-examples/
This code tracks what missiles players buy and sets the most recent 3 at the top of the list of missile options for players to easily buy them again. After players purchase missiles, the game crashes, but only if they purchase certain ones or purchase a certain amount.
Process: com.apps.fast.counterforcetest, PID: 16063
java.lang.IndexOutOfBoundsException: Index: 5, Size: 3
at java.util.LinkedList.checkElementIndex(LinkedList.java:555)
at java.util.LinkedList.remove(LinkedList.java:525)
at com.apps.fast.launch.components.ClientDefs.SetMissilePreferred(ClientDefs.java:199)
at com.apps.fast.launch.launchviews.PurchaseLaunchableView$1$1.onClick(PurchaseLaunchableView.java:198)
Here is the code the error points to in CLientDefs.java:199
public static void SetMissilePreferred(int lMissile) {
// Set a purchased missile to go to the top of the preferred list.
if (MissilePreferences == null)
MissilePreferences = new LinkedList<>();
if (MissilePreferences.contains(lMissile))
MissilePreferences.remove(lMissile); //<---- Line 199
MissilePreferences.push(lMissile);
if (MissilePreferences.size() > PREFERENCE_LIST_SIZE)
MissilePreferences.removeLast();
}
MissilePreferences is a List of Integers.
There's a bit of a mixup going on here:
if (MissilePreferences.contains(lMissile))
MissilePreferences.remove(lMissile);
lMissile is an int, right? Representing an ID? So when you call contains, you're checking if that ID exists in MissilePreferences. You want to know if the List contains that int.
Here's the method signature for contains:
public boolean contains(Object o)
It doesn't take a primitive like an int, it takes an Object - so your int is being autoboxed into an Integer - which makes sense because a List can't contain primitives either, only objects. MissilePreferences is a list of Integers.
So that's all fine, it converts your int to an Integer and tells you if it exists in the list of Integers, perfect! But then you call remove with that original int. And there are two versions of that method that take a parameter:
public boolean remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present.
public E remove(int index)
Removes the element at the specified position in this list.
Those do two very different things. The Object version removes the first instance of that object from the list. The int version treats the int as an index and removes whatever is in that position.
When you use contains, you're treating your int as an element in the list you want to find, and it's automatically converted to an Integer. And you want to do the same with remove - but there's a different version of that method that takes the int you're providing directly. It won't autobox that and call the other method, obviously! You'd have to do it yourself:
Integer missileId = new Integer(lMissile);
// explicitly passing an Integer object to both - only crucial for #remove
if (MissilePreferences.contains(missileId))
MissilePreferences.remove(missileId);
That's what you have to watch out for - outside of arrays and some special classes you might run into elsewhere, collection objects don't contain primitives, so you often want to explicitly work with the Object wrapper versions they contain. Especially important for ints because of situations like this!
That said, you could just do this:
MissilePreferences.remove(new Integer(lMissile));
No need to use contains - you can just call remove and it'll remove the first matching object if it has one. It returns true if it removed anything, in case you need to check that
Try debugging the code so that you know what are the elements in the list and what element is being removed. I am still confused as to how can you get an index out of bounds exception when you are just accessing the element from the list by its value.
When I tried self-answering this question, I could only find other questions regarding removing items from an array so that items past the removed object get moved down 1 in the index.
In the code below, I have two arrays that hold the class SomeObject (with a name property): SomeObject_ONE and SomeObject_TWO.
Below I put an object "some-object" in the first array, and then set the second array to equal the object in the first array. I can still change the properties of the object in the first array by changing the properties of the object in the second array (the 3rd indent.)
However, when I try setting the object in the second array to null, it doesn't set the first array to null, rather it only removes the index for the object in the second array (4th indent).
Is there anyway to delete an object in an array rather than removing its array index?
Thanks.
SomeObject[] ObjectArray_ONE = new SomeObject[10];
SomeObject[] ObjectArray_TWO = new SomeObject[10];
ObjectArray_ONE[0] = new SomeObject();
ObjectArray_TWO[0] = ObjectArray_ONE[0];
System.out.println(ObjectArray_ONE[0].name+" outputs default name");
ObjectArray_TWO[0].name = "Name changed from OA2";
System.out.println(ObjectArray_ONE[0].name+" outputs Name changed from OA2");
System.out.println("Should not be null : "+ObjectArray_ONE[0]);
ObjectArray_TWO[0] = null;
System.out.println("Should be null : "+ObjectArray_ONE[0]);
ObjectArray_ONE[0] = null;
System.out.println("Only now is it really null: "+ObjectArray_ONE[0]);
This is a Pass by Reference vs Pass by Value.
Java is pass by value, and in this case the value is a reference. It's a subtle distinction. What it means here is that if you change the object being referenced in one place, it will change everywhere. But it will not change the reference. If I set the reference to be equal to something else, the original object is unchanged.
The reason for this is exactly what Max said. Its the same reason that if you set one of your method parameters to null (inside the method) it won't affect the caller.
If you want you can store an array of wrapper classes of that object and then calling the setter of the wrapper class... Not exactly neat though.
PS. Don't capitalise variable names... it confuses people.
I have a function called resolveClash, which I send an array
(in this case - combinsFinal) with 2 or more objects in it of type ModuleLecturerStudentCombination (this is my own class). Essentially what the resolveClash function does is it puts the array into an arraylist, removes the first element/object in the array and then returns the list. However, when I inspect the state of the returned value in debug mode (eclipse), it shows that a null value has been added onto the end of the arraylist.
I have looked up "removing objects correctly" etc, however, everything I have tried so far doesn't get rid of the null. The null appears after I perform the remove. I have thoroughly checked that there is not a null being passed in etc. This is a problem because when I use this and iterate through it later, it picks up a null and gives me a nullpointerexception error. Could someone please let me know what I am doing wrong or point me in the right direction?
Thanks in advance!
picture displaying problem
resolveClash(combinsFinal);
public ArrayList <ModuleLecturerStudentCombination> resolveClash(ModuleLecturerStudentCombination[] combinationArr){
ArrayList<ModuleLecturerStudentCombination> copyCombinationList = new ArrayList<ModuleLecturerStudentCombination>(Arrays.asList(combinationArr));
copyCombinationList.remove(0);
return copyCombinationList;
}
...when I inspect the state of the returned value in debug mode, it shows that a null value has been added onto the end of the arraylist
This is the normal way it works. The data within the ArrayList is stored in an array, which then is wrapped in the class to behave in the way a list does. If you add elements and the array is to small it will create a bigger one and copy the objects.
However if you remove some, it wont create a new shorter array, but simply leave some free spots at the end, but only give you access to the first ones that should be their. In the Debug mode you should also see a variable called size which tells you which part of the array is still part of the list.
In your case the ArrayList method toArray(T []) is not returning a new array. From the documentation:
[...] If the list fits in the specified array, it is returned therein.
Otherwise, a new array is allocated with the runtime type of the
specified array and the size of this list.
If the list fits in the
specified array with room to spare (i.e., the array has more elements
than the list), the element in the array immediately following the end
of the collection is set to null. [...]
The array combinsFinal has greater size than the list so the result is returned directly into it with an additional null. In this case no new array with the correct size is created.
To avoid this, since you cannot change the size of an array, you could create a new one with the same size of the list, then this would work correctly:
combinsFinal = new ModuleLecturerStudentCombination[temp.size()];
temp.toArray(combinsFinal);
or alternatively just pass an array with no size so the method will be forced to create and return a new array with the correct size:
combinsFinal = temp.toArray(new ModuleLecturerStudentCombination[0]);
I've been learning how to program with java and I haven't got any clear explanation about the difference of LinkedList's toArray(T[] a) and toArray() method. The second one simply returns all of the elements within the LinkedList object as an array, right? But, what about the first one?
EDIT :
I mean, I read the documentation from oracle, it says :
Returns an array containing all of the elements in this list in proper
sequence (from first to last element); the runtime type of the
returned array is that of the specified array. If the list fits in
the specified array, it is returned therein. Otherwise, a new array is
allocated with the runtime type of the specified array and the size of
this list. If the list fits in the specified array with room to spare
(i.e., the array has more elements than the list), the element in the
array immediately following the end of the list is set to null. (This
is useful in determining the length of the list only if the caller
knows that the list does not contain any null elements.)
Like the toArray() method, this method acts as bridge between
array-based and collection-based APIs. Further, this method allows
precise control over the runtime type of the output array, and may,
under certain circumstances, be used to save allocation costs.
I don't understand the meaning of the sentences displayed in bold.
Suppose you've a List<String>, and you want to convert it to String[]. Let's see the working of two methods:
List<String> source = new LinkedList<String>();
// Fill in some data
Object[] array1 = source.toArray();
String[] array2 = source.toArray(new String[source.size()]);
See the difference? The first one simply creates an Object[], because it doesn't know the type of the type parameter <T>, while the second one just fills up the String[] you passed (which is what you want). You would almost always need to use the 2nd method.
There are two differences :
The first returns T[] while the second returns Object[]
The first accepts an array as an argument, and if this array is large enough, it uses this array to store the elements of the Collection, instead of creating a new one.