Index of an element in ArrayList of arrays - arrays

I have a list of two-element arrays that looks like this:
ArrayList<int[]> list = new ArrayList<int[]>();
I can get an element from this list using list.get(), but trying get the index of a known element doesn't work:
int[] array = list.get(0); //returns an array
int index = list.indexOf(array); //returns -1
I am using Processing 3.2.1
What am I doing wrong?

This will work:
ArrayList<int[]> list = new ArrayList<int[]>();
list.add(new int[]{1, 2});
int[] array = list.get(0);
int index = list.indexOf(array);
println(index);
This will not:
ArrayList<int[]> list = new ArrayList<int[]>();
list.add(new int[]{1, 2});
int[] array = new int[]{1, 2};
int index = list.indexOf(array);
println(index);
The indexOf() function uses the equals() function to figure out whether an object equals an element at each index. Unfortunately, arrays don't behave like you might expect, so two different arrays that have the same elements are not equal!
int[] arrayOne = {1, 2};
int[] arrayTwo = {1, 2};
println(arrayOne.equals(arrayTwo));
This is because arrays use instance equality, so arrays are only equal if they are the same exact array! That's why the first code block works, but the second one does not.
One way around this is to create a wrapper object that contains your arrays, and then override the equals() function to actually compare the elements in your arrays. But since your arrays only have two indexes, why don't you just create a class that has two variables, and then override the equals function? Or just use a PVector instance.

Related

C# - Tuple arrays are mutable, but tuple lists are not. How do I get around this?

I have an array of value pairs I want to modify. I need to add and remove values from this array as well, so I used a list. When I tried to use a list, I encountered an error.
Error CS1612 - Cannot modify the return value of 'List<(int, float)>.this[int]' because it is not a variable
So I decided I would investigate. I tried using an array instead, and it... worked fine? The following code only throws an error on arr1[0].Item1 += 1;.
static void Main()
{
List<(int, float)> arr1 = new List<(int, float)>() { (0, 0) };
(int, float)[] arr2 = new (int, float)[1];
arr1[0].Item1 += 1; // This line
arr2[0].Item1 += 1;
}
Why are tuple arrays mutable, but lists are not? Is this because arrays are simple blocks of data you can modify easily, but lists have a lot of backend behind them that complicates things? Is there a simple way to get around this, or am I going to have to make my own custom class?
Why are tuple arrays mutable, but lists are not?
The list itself is mutable, but not in the way you're doing it. Note that this isn't anything specific to tuples - it's just the case for any mutable struct.
The list indexer getter returns a value (i.e. a copy of the tuple in your case) - so modifying that value wouldn't modify the copy in the list. The compiler is trying to avoid you making a change to a value that's about to be thrown away. Array access doesn't do that - arr2[0] refers to the variable within the array. (An array is effectively a collection of variables.)
If you want to mutate the list, you can have to fetch the tuple, mutate it, then put it back:
var tuple = arr1[0];
tuple.Item1++;
arr1[0] = tuple;
Note that this also explains why you can't use list access expressions as arguments for ref parameters, but you can do the equivalent for arrays:
public void Method(ref int x) => x++;
public void CallMethod()
{
var list = new List<int> { 0 };
var array = new int[] { 0 };
Method(ref list[0]); // Error
Method(ref array[0]); // Valid
}

Multidimensional-array in Ceylon

I would like to work in Ceylon with a multidimensional array. Is this planned in Ceylon? If so, how can I declare it?
I would like to use this construct in Ceylon, as shown here in Java:
int x = 5;
int y = 5;
String[][] myStringArray = new String [x][y];
myStringArray[2][2] = "a string";
First, consider whether you really need an array (i.e. something with fixed length and modifiable elements), or whether a list (or list of lists) or a map might be better. Though from your example, you seem to need modification.
In the JVM, a "multidimensional" array is just an array of arrays.
In Java, new String[y] creates an array filled with null entries, which is not an allowed value of type String in Ceylon. So you can either have an array of String? (which allows null), or pre-fill your array with some other value, using e.g. Array.ofSize(...):
Array.ofSize(y, "hello")
The same is valid for arrays of arrays. We could do this:
value myStringArray = Array.ofSize(x, Array.ofSize(y, "hello"));
Though this would have the same array in each "row" of the 2D-array, which is not what we want (as replacing myStringArray[2][2] would replace all entries with a 2 as the second coordinate). Here the other Array constructor is useful, which takes an iterable:
value myStringArray = Array({ Array.ofSize(y, "hello") }.repeat(x));
This takes advantage of the fact that the iterable enumeration evaluates its arguments lazily, and thus the array constructor will get x different elements.
I like Paulo's answer, but here's an alternative approach, which allows us to use a comprehension to populate the 2D array:
//the size of the square 2D array
value n = 5;
//create it using a nested comprehension
value arr = Array {
for (i in 1..n-1) Array {
for (j in 0..n-1)
i==j then 1 else 0
}
};
//display it
for (row in arr) {
printAll(row);
}

Arrays inside a Arraylist

i need to build up an ArrayList with Integer in new Arrays in it. How can I setup this and add items?
private final ArrayList<Integer>[] test;
test = new ArrayList<Integer>();
This won't work.
Thank you!
An array is an Object, and you can make lists of any object type - so you can make a List of arrays without doing anything special:
// Declare it and initialise as an empty list
List<Integer[]> list = new ArrayList<>();
// Add an item -- it's a new array
list.add(new Integer[5]);
// Access an item -- it's an array
Integer[] array = list.get(0);
Integer x = array[0];
I see few reasons to use arrays of Integer for most situations, however. An array of int is also an Object so you can use that just as well.
List<int[]> list = new ArrayList<>();
list.add(new int[5]);
One of the most common reasons for using the object Integer rather than the primitive int is that you can't have Lists of primitives. But you can have arrays of primitives, so if you're happy with the lesser expressive power of the array, by all means populate it with primitives.
Ask yourself why you want a List of arrays rather than a List of Lists, an array of arrays or an array of Lists, however.
Your question asks for "Arrays inside an ArrayList".
List<Integer[]> is a list of arrays (because, inside the <>, is Integer[]).
List<Integer>[] is an array of lists -- "ArrayLists inside an array" -- because the [] comes after the List<> declaration.
You can initialise your array of lists just like any other array, with new Type[length]:
// Declare it
List<Integer>[] array = new List<Integer>[5];
// Put something into an array element
array[3] = new ArrayList<Integer>();
// Access an element -- it's a List
List<Integer> list = array[3];
Integer x = list.get(0);
Looks like you want to create a 2-dimansional integer array.
I assume you have a special use case in which you need a primitive array ob ArrayList-Objects.
Anyways you can create such a thing like any other primitive array
like
ArrayList<Integer>[] test = new ArrayList[2];
and access/set it by index..
test[0] = new ArrayList<Integer>();
You also can fill the array on init...
ArrayList<Integer>[] test = new ArrayList[] {
new ArrayList<Integer>(),
new ArrayList<Integer>(),
new ArrayList<Integer>()
};
If we want Arrays inside List then -
class Test {
private final List<int[]> myList;
public Test() {
myList = new ArrayList<>();
}
public void add(int[] myArray) {
myList.add(myArray);
}
}
You are always allowed to initialize a final variable. The compiler makes sure that you can do it only once.
u can use like this for do this
private ArrayList<Integer>[] test ;
private void test(int n){
test=new ArrayList[n];
for(int i=0;i<n;i++){
test[i]=new ArrayList<Integer>();
test[i].add(100);
test[i].add(10);
test[i].add(10000);
test[i].add(1);
....
}
}

Select specific item in Arraylist of arrays

I'm working with Processing and I have an Arraylist of arrays
ArrayList< ICurve []> c = new ArrayList< ICurve []> ();
I need to select a specific item in a specific array of my arraylist, but I can't understand how to do it. I know how to iterate inside the arraylist with the for cycle, but I can't understand how to select the item with a specific index.
Thanks in advance for your help!
An Arraylist of arrays returns an array, so just use bracket notation:
ArrayList <Integer[]> a = new ArrayList <Integer[]> ();
void setup(){
a.add(new Integer[] {1,2,3});
println(a.get(0)[1]);// prints 2
}
ArrayList< int[] > myArrayList = new ArrayList< int[]> ();
void setup()
{
int[] myArray = {0, 1, 2, 3};
myArrayList.add(myArray);
println(myArrayList.get(0)[0]);
}
I've used a primitive datatype in this example, but the same principle applies.

Converting an int array list to an int array

EDIT:
I am trying to add elements read from a txt document line by line into an array list then convert that array list into an array. Although I am getting errors with my code. It doesnt like the int[] a = lines.toArray(new int[lines.size()]);.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class insertionSort {
public static void main(String[] args) {
List<Integer> lines = new ArrayList<Integer>();
File file = new File("10_Random.txt");
try {
Scanner sc = new Scanner(file);
//int line = null;
while (sc.hasNextLine()) {
int i = sc.nextInt();
lines.add(i);
//System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
int[] a = lines.toArray(new int[lines.size()]);
}
}
Edit2: Thanks chaitanya10! all fixed.
int line= null; is wrong,
"null is a special literal that can be of any object reference type".you cant assign null to primitive variables in java like (int, byte, float...). null can only be assigned to objects . remember thatnullis the default vale forobjects` when you don't initialize them.
if you wanna access int as an object use Integer.
Integer line= null;//nowthis would compile
and to convert an list onto array do this.
List.toArray(T[] t) method returns an Object.
do like below.
Integer[] array = lines.toArray(new Integer[lines.size()])
and also your List accepts int[] array and you are tryig to add an int into the list .
change your List declaration like this
List<Integer> lines = new ArrayLis<Integer>();
To print the elements in the array you have to iterate over it
for(int i=0; i<a.length;i++){
system.out.println(a[i])
}
you seem to be a beginner in java. strongly recommend you tohereread about java basic
Two main problems.
You can't assign null to an int. null is a pointer value, and ints in Java are always handled by value, not by reference. Objects can be null, primitive values like int and double can't.
The type declaration of your ArrayList is wrong. The way you're assigning it, each element of the list is expected to be an array of ints. I don't think that's really what you want - the each element is just one int value, so that the list as a whole is analogous to an array.
The second bullet is the reason behind your second and third errors, which I think you'd probably see if you read the error messages all the way through (it's a TypeMismatch error, right?). With your list parameterized to int[], the add method is expecting everything that's added to be of the type int[]. But line is only an int. Similarly, the toArray() method returns an array of whatever type the list is parameterized with. Since you have a list of arrays, toArray() will return an array of arrays. Its return type in this case is int[][], which can't be assigned to int[] a because the type doesn't match.
This should get your code to compile, but it doesn't get into the other issues of validation and whatnot that you have to worry about any time you have input... but for now I'm just going to assume that you've already vetted the input file.
You can use IntStream:
int[] arr = {15, 13, 7, 4, 1, 10, 0, 7, 7, 12, 15};
List<Integer> arrayList = IntStream.of(arr).boxed().collect(Collectors.toList());
System.out.println(arrayList);

Resources