I tried to find what's wrong with this simple code, I tried to search on this website for sample but could't find it.
I want to create list of arrays. So when I call myList.get(0) it will output first array1. And if myList.get(0)[0] the very first value.
Thank you
My code:
List<int[]> myList = new ArrayList<int[]>();
int[] array1 = {15, 20, 40};
int[] array2 = {30, 7, 18};
myList.add(array1);
myList.add(array2);
System.out.println(myList);
Gives this kind of output. [[I#129f3b5, [I#13f3045]
You have to do something like this, import java.util.Arrays and use this static method Arrays#toString(int[])
for(int[] a : myList) {
System.out.println(Arrays.toString(a));
}
In your example myList.get(0) will return an array of ints, because that's what your list contains.
So if you want to print all the elements of the array you should do something like
for (int[] array : myList) {
for (Integer i : array) {
System.out.println(i);
}
}
This will first print out each value on a new line, now you should probably edit the output by yourself. And the second loop will print out each table using Arrays.toString()
public static void main(String[] args) {
List<int[]> myList = new ArrayList<int[]>();
int[] array1 = { 15, 20, 40 };
int[] array2 = { 30, 7, 18 };
myList.add(array1);
myList.add(array2);
for (int[] tables : myList)
for (int i : tables)
System.out.println(i);
//This is also possible
for (int[] tables : myList)
System.out.println(Arrays.toString(tables));
}
Unfortunately, Java arrays don't have a good toString() method that would return a well-formatted view of the elements it contains. And System.out.println(Object) actually calls this bad toString() method, which simply returns the type of the array ([[I) followed by its hash code.
To get a meaningful representation of an array, use java.util.Arrays.toString():
for (int[] array : myList) {
System.out.println(Arrays.toString(array);
}
You should print it like that:
for(int i = 0; i < myList.size(); i++) {
int[] numbers = myList.get(i);
System.out.println(Arrays.toString(numbers));
}
Array is Object, and as you know, each object has toString method. The default toString displays the class name representation, then adds # and then the hashcode.
You can use Arrays.toString() to print the array. ;
System.out.printlin(myList.get(0)) // first Array from the list
System.out.printlin(myList.get(1)) // second Array from the list
Use below code to print entire list.
for(int[] array : myList) {
System.out.println(Arrays.toString(array));
}
The code is correct. However, you have to remember that you can't simple print an array, but have to do something like
System.out.println(Arrays.toString(myList));
The
I#129f3b5
I#13f3045
are the default toString() implementations for arrays.
So the code is completely correct, the arrays are stored in the list. Just the toString() is not of much use for arrays.
Simply - you should not rely on array toString().
Related
I want to randomize or shuffle the order of the string array using the code below
public static void main(String[] args) {
String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
String strTmp[]=str;
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=0; i<str.length; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
for (int i=0; i<str.length; i++) {
strTmp[i]=str[list.get(i)];
System.out.println(strTmp[i]);
}
}
The reason I do it like this instead of print it out directly is because I want to make it into a function later on. That's why I passed it to strTmp[] as that is what I want the function to return. But, the code just didn't function as I expected. It prints out several same value. How can I do it the right way? Thanks for the answer...
You almost had it, but you are referencing the same array twice and swap the contents of it. Change this line
String strTmp[] = str;
to
String strTmp[] = new String[str.length];
If you don't want to change the array str. Try this.
String str[] = {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
String strTmp[] = str.clone();
Collections.shuffle(Arrays.asList(strTmp));
System.out.println(Arrays.toString(strTmp));
output
[Xcgi, Cvda, Atdr, Mbeds, 0bda, Vxds]
When you do String strTmp[]=str;, both str and strTmp are references to the same array. So when putting elements in, you are overwriting old elements including those have not yet been moved.
You may just do
String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
Collections.shuffle(Arrays.asList(str));
This works because Arrays.asList() does not create a new list, it merely provides a list view on the array. Any changes to the list change the array. Including shuffling it. Edit: This works for an array of strings and an array of any other reference type. As WJS points out, this will not work for an array of primitives (e.g., int[]) since Arrays.asList(arrayOfPrimitives) will create a list view of a newly created array of one elemeent, the primitive array.
If you require a new array with the shuffled strings and the old array unmodified, the solution is:
List<String> list = new ArrayList<>(Arrays.asList(str));
Collections.shuffle(list);
String[] newStr = list.toArray(new String[0]);
System.out.println("Original array: " + Arrays.toString(str));
System.out.println("New shuffled array: " + Arrays.toString(newStr));
Edit: Output from one example run:
Original array: [Vxds, Cvda, Xcgi, Atdr, Mbeds, 0bda]
New shuffled array: [0bda, Cvda, Mbeds, Vxds, Xcgi, Atdr]
As you can see, the original array is unmodified.
Edit: Since Java 11 it’s nicer to create the new array using Collection.toArray(IntFunction<String[]>):
String[] newStr = list.toArray(String[]::new);
See both code snippets run live in IdeOne.
I understand that you want to randomized your array in every execute. Here is the code for this.
import java.util.*;
public static void main(String[] args) {
String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
List<String> list =Arrays.asList(str);
Collections.shuffle(list);
System.out.println(list);
}
I need the simplest way to add an item to the front of an Java array.
I need the Java array NOT the ArrayList.
There are two ways to do this. One, using Objects or another using generics. I recommend you to use generics because gives you more flexibility as you gonna see in these examples.
In this first implementation the function add2BeginningOfArray is using generics:
public static <T> T[] add2BeginningOfArray(T[] elements, T element)
{
T[] newArray = Arrays.copyOf(elements, elements.length + 1);
newArray[0] = element;
System.arraycopy(elements, 0, newArray, 1, elements.length);
return newArray;
}
Calling this function is really simple. For instance, if you have a class Dot and you want to add an element to the beginning of an array of Dot objects you just need to do this:
int size = 20;
Dot[] dots = new Dot[size];
for (int i = 0; i < size; i++) {
dots[i] = new Dot("This is a dot");
}
Dot goal = new Dot("This is a goal");
System.out.println(Arrays.toString(add2BeginningOfArray(dots, goal)));
You can also implement a function declaring the function parameters as Object as shown in this example:
public static Object[] add2BeginningOfArray(Object[] elements, Object element){
Object[] tempArr = new Object[elements.length + 1];
tempArr[0] = element;
System.arraycopy(elements, 0, tempArr, 1, elements.length);
}
Now, what is the problem? Well, not a big problem but now you need to declare your array as Object[] and use this kind of declaration to work with it.
Object[] foo = {"2", "3", "4"};
//adding an element to the beginning array
Object[] numbers = add2BeginningOfArray(foo, "1");
System.out.println(Arrays.toString(numbers));
For me the generics approach is cleaner and more scalable, so I really recommend it over the Object approach.
Apache Commons Lang class 'ArrayUtils' makes this very easy, if that is an option for you:
char[] arrayA = {'b', 'c'};
char[] arrayB = ArrayUtils.add(arrayA, 0, 'a');
// arrayB: [a, b, c]
for(int i = roadVehicles.length; i > 0; i--) {
if (roadVehicles[i-1] != null) {
roadVehicles[i] = roadVehicles[i-1];
}
}
roadVehicles[0] = car;
As per the Java tutorials (which I thoroughly recommend beginners to work through)
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
Because arrays cannot be resized - you can overwrite the first element, but to perform an insert you must create a new array 1 larger than the previous one, put your new element in the first position and fill the rest of the array with the existing elements.
Of course, in practice don't do this. Instead use a collection that suits your actual use-case.
So the actual answer to your question is: The simplest way to add an item to front of a java array is to use a better collection type such as a Deque.
I cannot think of any valid reason in Java to not use a more appropriate collection than a raw array if inserting to the front is required.
Once created an array cannot be resized. If you have to add an element you'll need to create a new array.
If you know the array type it's trivial, but a nicer solution will work with any array type, using the java.lang.reflect.Array
Example code:
public static Object addElementInFrontOfArray(Object array, Object element) {
int newArraySize = Array.getLength(array)+1;
Object newArray = Array.newInstance(element.getClass(), newArraySize);
//Add first element
Array.set(newArray, 0, element);
for (int i=1 ; i<newArraySize; i++) {
Array.set(newArray, i, Array.get(array, i-1));
}
return newArray;
}
Consider that you can pass a int[] array as parameter but a Integer[] arrary will be returned
Considering this source
https://www.journaldev.com/763/java-array-add-elements
you can add new elements at the beginning of you array by doing this:
public static Object[] add(Object[] arr, Object... elements){
Object[] tempArr = new Object[arr.length+elements.length];
System.arraycopy(arr, 0, tempArr, elements.length, arr.length);
for(int i=0; i < elements.length; i++)
tempArr[i] = elements[i];
return tempArr;
}
Why not just use an ArrayList?
You could use an Array convert it to a List as follows:
List<Integer> myList = Arrays.asList(1,2,3);
//Instead of 1,2,3 you could create an Integer array: Integer[] myArray = {1,2,3};
myList.add(0, 25);
If you decide doing this way, you could check the answers of this question:
Java Arrays how to add elements at the beginning
or just check out the documentation:
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
here's a concrete example of the simplest way I could find:
List<StackTraceElement> stack = new ArrayList<StackTraceElement> (Arrays.asList (e.getStackTrace()));
stack.add (0, new StackTraceElement ("class", "method", "file", 25439));
StackTraceElement[] newStack = new StackTraceElement[stack.size()];
newStack = stack.toArray (newStack);
e.setStackTrace (newStack);
Basically it uses java.util.Arrays.asList() to turn the array into a List, adds to the list and then turns the list back into an array with List.toArray().
As everybody has said, you can't really add to the beginning of an array unless you shift all the elements by one first, or as in my solution, you make a new array.
Just .unshift()
This adds an element to the beginning of an array.
I am trying to sort an array of integers from highest to lowest.
int[] array = {2, 6, 4, 1};
Arrays.sort(array);
Collections.reverse(Arrays.asList(array));
for (int num : array) {
System.out.println(num);
}
This prints the array in an ascending order - 1, 2, 4, 6. Why is it not being reversed, or why is the array not being permanently stored in its reversed state?
The most "easy" solution would be to use the reverseComperator provided by the Collections class. This will automaticly sort the array in a descending order.
public static void main(String[] args) {
// Use the Wrapper class, otherwise you can´t call Arrays.sort with a comperator.
Integer[] array = {2, 6, 4, 1};
Arrays.sort(array, Collections.reverseOrder());
for (int num : array) {
System.out.println(num);
}
}
As why your solution doesn´t work.
You temporarly create a List with Arrays.asList(array), which you do reverse and that isn´t refered to anymore afterwards. This wont change the order for the array variable.
You're displaying the result of sorting the array, not the result of reversing the list. You would need to store the sorted list in a temporary variable, reverse it, then call toArray to get the desired behavior.
The more straightforward way to sort in reverse order is to do:
Arrays.sort(array, (o1,o2)-> Integer.compare(o2,o1));
There are several problems in your code: Arrays.asList does not create a new List<Integer>, it's actually a List<int[]>. But even if it worked as you expected, the returned list is only a temporary object, you're still printing the array.
Unfortunately, the correct solution is not very elegant:
int[] array = {2, 6, 4, 1};
Arrays.sort(array);
List<Integer> asList = new ArrayList<Integer>();
for(int i : array) {
asList.add(i);
}
Collections.reverse(asList);
for (int num : asList) {
System.out.println(num);
}
I'm trying to get the basics of ArrayLists, but I can't get the lastIndexOf method to work properly. As you can see in my code below, the program runs and should print "1", the index of the number 3, but prints "-1" instead (which should be printed only if 3 didn't exist in the ArrayList). What's my problem?
import java.util.ArrayList;
public class Pile {
public static void main(String[] args)
{
int[] myArray = {1,3,23,4};
ArrayList<Integer> myList = new ArrayList<Integer>();
for (int i=0;i<myArray.length;i++) {
myList.add(myArray[0]);
}
System.out.println(myList.lastIndexOf(3));
}
}
You're only adding the first element of myArray to myList
You should replace
myList.add(myArray[0]);
with this
myList.add(myArray[i]);
Also, instead of manually copying the elements, you could use Arrays#asList (but you would need to change the type of myArray to Integer[]):
List<Integer> myList = Arrays.asList(myArray);
You are only adding the first element of the array multiple times to the list.
myList.add(myArray[0]);
That's why your list doesn't contain 3.
Change it to
myList.add(myArray[i]);
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 8 years ago.
What I am trying to do is add an array to an arraylist. I've looked at other examples that tell me to do what I am doing, but I get nonsense output when I run the program. I would also like to access certain elements of an array within the arraylist, and I have no idea how to do that.
static int elements = 10; //Or whatever number you'd like
public static void main(String[] args)
{
int[] person = new int[4];
ArrayList personID = new ArrayList();
experiment(personID, person);
}
private static void experiment(ArrayList personID, int[] person)
{
for(int i = 0; i < elements; i++)
{
person[0] = i;
person[1] = i;
person[2] = i;
person[3] = i;
personID.add(person);
}
System.out.print(personID);
}
Output:
[[I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87]
Not that much of an explanation is needed, but I declare the array and arraylist, pass them to a function which keeps giving the array's elements different values and then, supposedly, adding the array itself to the arraylist for each iteration.
The output, though, it nothing like what I am looking for. I could do another loop to print each array element for each spot along the array list, but I don't know how to do that. I figured
System.out.print(personID.get(i[0]);
Or
System.out.print(personID.get(i)[0];
But it doesn't work and I'm lost...
Thank you for dealing with me!
It's just a problem with the way you're printing the arrays. Try this instead:
for (int[] a : personID)
System.out.println(Arrays.toString(a));
Not only are you attempting to print arrays by implicitly invoking toString, but also adding the same array over and over to the list. The variable called person is a reference to an array object. You keep changing its elements and adding the same reference.
Were your print routine to be correct, the output would only show an array of four 10s repeated 10 times.
Arrays doesn't implement its own toString() implementation it uses Object#toString() and that is why you are watching that output
getClass().getName() + '#' + Integer.toHexString(hashCode())
[I means that is an Integer array plus # followed with it's hashcode e1cba87.
One way to solve it is using Arrays.toString()
For example:
public static void main(String[] args){
int[] person = new int[4];
List<int[]> personID = new ArrayList<>();
experiment(personID, person);
//now print
for(int[] array : personID){
System.out.println(Arrays.toString(array));
}
}