ArrayList of int array in java - java

I'm new to the concept of arraylist. I've made a short program that is as follows:
ArrayList<int[]> arl=new ArrayList<int[]>();
int a1[]={1,2,3};
arl.add(0,a1);
System.out.println("Arraylist contains:"+arl.get(0));
It gives the output: Arraylist contains:[I#3e25a5
Now my questions are:
How to display the correct value i.e. 1 2 3.
How can I access the single element of array a1 i.e. if I want to know the value at a1[1].

First of all, for initializing a container you cannot use a primitive type (i.e. int; you can use int[] but as you want just an array of integers, I see no use in that). Instead, you should use Integer, as follows:
ArrayList<Integer> arl = new ArrayList<Integer>();
For adding elements, just use the add function:
arl.add(1);
arl.add(22);
arl.add(-2);
Last, but not least, for printing the ArrayList you may use the build-in functionality of toString():
System.out.println("Arraylist contains: " + arl.toString());
If you want to access the i element, where i is an index from 0 to the length of the array-1, you can do a :
int i = 0; // Index 0 is of the first element
System.out.println("The first element is: " + arl.get(i));
I suggest reading first on Java Containers, before starting to work with them.

More simple than that.
List<Integer> arrayIntegers = new ArrayList<>(Arrays.asList(1,2,3));
arrayIntegers.get(1);
In the first line you create the object and in the constructor you pass an array parameter to List.
In the second line you have all the methods of the List class: .get (...)

Use Arrays.toString( arl.get(0) ).
arl.get(0)[1]

The setup:
List<int[]> intArrays=new ArrayList<>();
int anExample[]={1,2,3};
intArrays.add(anExample);
To retrieve a single int[] array in the ArrayList by index:
int[] anIntArray = intArrays.get(0); //'0' is the index
//iterate the retrieved array an print the individual elements
for (int aNumber : anIntArray ) {
System.out.println("Arraylist contains:" + aNumber );
}
To retrieve all int[] arrays in the ArrayList:
//iterate the ArrayList, get and print the elements of each int[] array
for(int[] anIntArray:intArrays) {
//iterate the retrieved array an print the individual elements
for (int aNumber : anIntArray) {
System.out.println("Arraylist contains:" + aNumber);
}
}
Output formatting can be performed based on this logic. Goodluck!!

In java, an array is an object. Therefore the call to arl.get(0) returns a primitive int[] object which appears as ascii in your call to System.out.
The answer to your first question is therefore
System.out.println("Arraylist contains:"+Arrays.toString( arl.get( 0 ) ) );
If you're looking for particular elements, the returned int[] object must be referenced as such.
The answer to your second question would be something like
int[] contentFromList = arl.get(0);
for (int i = 0; i < contentFromList.length; i++) {
int j = contentFromList[i];
System.out.println("Value at index - "+i+" is :"+j);
}

You have to use <Integer> instead of <int>:
int a1[] = {1,2,3};
ArrayList<Integer> arl=new ArrayList<Integer>();
for(int i : a1) {
arl.add(i);
System.out.println("Arraylist contains:" + arl.get(0));
}

Everyone is right. You can't print an int[] object out directly, but there's also no need to not use an ArrayList of integer arrays.
Using,
Arrays.toString(arl.get(0))
means splitting the String object into a substring if you want to insert anything in between, such as commas.
Here's what I think amv was looking for from an int array viewpoint.
System.out.println("Arraylist contains: "
+ arl.get(0)[0] + ", "
+ arl.get(0)[1] + ", "
+ arl.get(0)[2]);
This answer is a little late for amv but still may be useful to others.

For the more inexperienced, I have decided to add an example to demonstrate how to input and output an ArrayList of Integer arrays based on this question here.
ArrayList<Integer[]> arrayList = new ArrayList<Integer[]>();
while(n > 0)
{
int d = scan.nextInt();
Integer temp[] = new Integer[d];
for (int i = 0 ; i < d ; i++)
{
int t = scan.nextInt();
temp[i]=Integer.valueOf(t);
}
arrayList.add(temp);
n--;
}//n is the size of the ArrayList that has been taken as a user input & d is the size
//of each individual array.
//to print something out from this ArrayList, we take in two
// values,index and index1 which is the number of the line we want and
// and the position of the element within that line (since the question
// followed a 1-based numbering scheme, I did not change it here)
System.out.println(Integer.valueOf(arrayList.get(index-1)[index1-1]));
Thanks to this answer on this question here, I got the correct answer. I believe this satisfactorily answers OP's question, albeit a little late and can serve as an explanation for those with less experience.

java.util.Arrays.toString() converts Java arrays to a string:
System.out.println("Arraylist contains:"+Arrays.toString(arl.get(0)));

ArrayList<Integer> list = new ArrayList<>();
int number, total = 0;
for(int i = 0; i <= list.size(); i++){
System.out.println("Enter number " + (i + 1) + " or enter -1 to end: ");
number = input.nextInt();
list.add(number);
if(number == -1){
list.remove(list.size() - 1);
break;
}
}
System.out.println(list.toString());
for(int i: list){
System.out.print(i + " ");
total+= i;
}
System.out.println();
System.out.println("The sum of the array content is: " + total);

Integer is wrapper class and int is primitive data type.Always prefer using Integer in ArrayList.

List<Integer> integerList = IntStream.range(0,100)
.boxed()
.toList();
This is one of the ways, you can initialize the fixed size ArrayList in Java using Java8+ - Stream API. integerList is going to contain integer values from 0 to 99.

Related

How can I print all common numbers in three inputted user arrays?

int ar1, ar2, ar3;
System.out.print("Enter size of the 1st array: ");
//reading the number of elements from the that we want to enter
ar1 = sc.nextInt();
System.out.print("Enter value of the 1st array: ");
for (int i = 0; i < ar1; i++) {
array[i] = sc.nextInt();
}
System.out.println("Array1: ");
for (int i = 0; i < ar1; i++) {
System.out.println(array[i] + " ");
}
What can I add to print the common numbers in three inputted numbers in arrays?
first of all - arrays are primitive and quite a pain if it comes to using them. An alternative would be using ArrayList. But since you’re using arrays in this question, this would be an idea to solve the problem:
When your arrays are set up you can iterate through them to compare them. To do that you could declare 2 additional arrays:
int[] matchesA1A2 = new int[array1.length];
int[] matchesAll = new int[array1.length];
where machesA1A2 will contain the values that are both in array1 and array2. And matchesAll ALL the matching numbers.
Now just iterate through the first array comparing it with the second one to find which values match. Like that:
for (int i = 0; i<array1.length; i++){
for (int i2 = 0; i2<array2.length; i2++){
if (array1[i]==array2[i2]){
matchesA1A2[i] = array1[i];
}
}
}
The first two array are now compared. Now you can iterate through the third array comparing it witch the MATCHES of the array1 and array2 (which is the matchA1A2 array). Like this:
for (int i3 = 0; i3<array3.length; i3++){
for (int im = 0; im<matchesA1A2.length; im++){
if (array3[i3]==matchesA1A2[im]){
matchesAll[i3] = array3[i3];
}
}
}
If you println the matchesAll array you should see something, like this: [0, 0, 0, number, 0, 0, number, 0, 0…]
System.out.println(Arrays.toString(matchesAll));
Alle the “numbers” in the array are values that match in all three arrays.
Disclaimer: this is not the best way to write code, but I think because of the way it’s written it is easier for beginners to understand the concept of iterating.

Why does this method only return values of 0 to a new array?

I am supposed to write a short program that takes 10 numbers, stores the values in an array, passes it to a method (eliminateDuplicates()) that creates a new array of only the unique values from the first array.
However, I am having trouble either initializing the output array, or making the eliminateDuplicates() method return the output array properly. The output array is always full of 0's and I cannot figure out why this is failing.
java.util.Arrays.parallelSort(inputNumbers); //sorts the array in ascending order
eliminateDuplicates(inputNumbers); //passes array to eliminateDuplicates method
//display each unique value in output array
System.out.print("The distinct numbers are ");
for(int i = 0; i < outputNumbers.length; i++)
System.out.print(outputNumbers[i] + " ");
}
public static int [] eliminateDuplicates(int[] list) {
int[] outputNumbers = new int [list.length];
int k = 0;
for (int i = 0; i < list.length; i++)
if(i == 0) //compares each array value against preceding value
outputNumbers[i] = list[i]; //only copies unique values to output array
else
if(list[i] != list [i-1]) {
outputNumbers[k] = list[i];
k++;
}
return outputNumbers;```
You have a local outputNumbers in eliminateDuplicates which you return. I assume you also have a redundant static outputNumbers. Option 1: Eliminate the local variable, change
int[] outputNumbers = new int [list.length];
to
outputNumbers = new int [list.length];
Option 2: Set outputNumbers on call (which is what I would likely do, and eliminate the static one)... Like,
int[] outputNumbers = eliminateDuplicates(inputNumbers);
Don't forget to remove the static one if you use option 2.
You are ignoring the array returned by your method.
Change
eliminateDuplicates(inputNumbers);
to
int[] outputNumbers = eliminateDuplicates(inputNumbers);
P.S. your output array has the same length as the input array. Therefore, since you are eliminating duplicates, it may have some 0s as its last elements. If that's not what you want, you should create the output array only after you find out how many unique numbers the input array has.

How to print Java array values with one particular id?

I am new to Java. I have one array with values but I want to print the values with id that mean{"id":1} My array with values are
int[] arr={1,2,3,4,5};
I want to print output values like below
{"id":1},{"id":2},{"id":3},{"id":4},{"id":5}
Is it possible in Java?
You can iterate over the array and just
int[] arr = {1,2,3,4,5};
for(int a : arr){
System.out.println("{id:" + a + "}");
}
Where "a" is a short life variable that takes the value of each element in the array "arr"
This way you can print {id:1} with this short code.
You can do as follow :
int[] arr = {1,2,3,4,5};
String id = "\"id\"";
for(int i = 0 ; i <=arr.length; i++){
System.out.println("{"+id+": " + arr[i] + "}");
}
Here's the way to do it in recent Java versions (8 or higher)
System.out.println(
Arrays.stream(arr) // stream over int array
.mapToObj(i -> "{\"i\":" + i + "}") // convert int to custom String
.collect(Collectors.joining(", ")) // join Strings using a comma
) // print the big string

How to find the Missing Elements in a given sequence array list using java?`

1.I have an Integer array list with a starting element and arraylist limit.
Example [5,6,9,10]
2.In which I have to iterate and find the missing element and its position.
According to the above example ,my output should be number 7 (position3 ),number 8 (position 4) are missing.
3.Now I am getting all the numbers printed instead of getting the missing elements.
Below is the code :
public static List<Integer> issue_ret=new ArrayList<>();
Iterator<Integer> iter = issue_ret.iterator();
while(iter.hasNext()){
int value = iter.next();
if("1".equals(value)){
iter.remove();
}
else{
System.out.println("Missing value:"+value);
}
}
Can anyone help me to resolve this?
Suggest you a more efficient way than ArrayList.contains() but more limited:
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(new Integer[]{5, 6, 9, 10}));
int head = list.get(0);
int tail = list.get(list.size() - 1);
int length = tail - head + 1;
int[] array = new int[length];
for (int i : list) {
array[i - head] = 1;
}
for (int i = 0; i < array.length; i++) {
if (array[i] == 0) {
System.out.println(String.format("Missing %d, position %d", i + head, i + 1));
}
}
The limit is: The top Integer number should not be too large. Anyway, it is a space for time way, whether to use depends on your actual needs.
You are comparing every element with 1
if("1".equals(value))
instead you should keep a counter which will start from your lists first element and then incremented by 1 and perform comparison with this counter.
Try,
List<Integer> integerList = new LinkedList<Integer>();
integerList.add(5);
integerList.add(6);
integerList.add(9);
integerList.add(10);
int first = integerList.get(0);
int last = integerList.get(integerList.size()-1);
for(int i=first+1; i<last; i++){
if(!integerList.contains(i))
System.out.println("Number Not in List : "+i);
}
By getting the first and last element from array you can know the start and end of the array and by iteration over that limit you can get what numbers are missing like below:
List<Integer> input = new ArrayList<Integer>();
input.add(5);
input.add(8);
int firstElement = input.get(0);
int lastElement = input.get(input.size()-1);
for(int i=firstElement+1, j=2; i<lastElement-1; i++,j++){
if(!input.contains(i))
System.out.println("Missing Number : "+i + "(position " + j+")");
}
As we already know that first element and last element is already present in last, no need to check that so we would be only checking of elements exist between first and last element.

Java code, array/matrix component

I have this 3x1 array/matrix in java. How can i use any one of the single components of the array. Lets say i want to
r = Math.pow(second row component,2) + Math.pow(third row component,2)
What is the calling code for the components?
Thanks
Use a foreach to iterate through the array, and then add Math.Pow index by index
double[] myArray = { 1.2, 16.5, 20.0 }
double r = 0;
for(double d : myArray)
{
r+= Math.pow(d,2);
}
If by components you mean elements, then the syntax is as follows:
int[] numbers = {1,2,3,4,5};
int num = numbers[0];
System.out.println("Number: " + num);
// Outputs Number: 1
Extra Reading
You should read the documentation. This contains all of the information you need to use the array type in Java.
If you want to access an element of an array, apend the index of the element in brackets:
r = Math.pow(second row component,2) + Math.pow(third row component,2)
becomes
r = Math.pow(arrayVariable[1],2) + Math.pow(arrayVariable[2],2)
Remember, array indexes are base zero.

Categories