Home > Back-end >  Creating HashSet from float[][] array
Creating HashSet from float[][] array

Time:02-21

I just started learning Java and barely know about primitive class and a data type, and I was trying to create a set for every array inside another array. But when I tried doing it the result wasn't a set of the contents of the inner array, but a set of the array itself.

In Python I would just do:

mylist = [[1, 1, 1], [0, 0, 0], [0, 0, 0]]
for inner in mylist:
    s = set(inner)

And s would just be 1, 0, 0 (for each loop).

But when I tried implementing this in Java I got a size of 1 (which would be correct for my example) but when I displayed the set's items it's a random set of letters and numbers (I saw in another post that this is a memory address). I was just hoping anyone would point out where my mistake is and how to implement it correctly.

Code:

public class Test {
    private static final int HOURS = 24;
    private static final int DAYS = 3600;
    private static float[][] mylist = new float[DAYS][HOURS];
    
    private static void set_loop(float[][] myList) {
        for (int k = 0; k < myList.length; k  ) {
            Set<float[]> mySet = new HashSet<>(Arrays.asList(myList[k]));
            System.out.println("------------------");
            System.out.println(mySet.size());
            for (float[] s : mySet) {
                System.out.println(s);
            }           
        }
    }
    
    public static void main(String[] args) {
        for (int k = 0; k < mylist.length; k  ) {
            for (int i = 0; i < mylist[k].length; i  ) {
                if (k == DAYS - 2) {
                    mylist[k][i] = 9;
                } else {
                    mylist[k][i] = 0;
                }
            }           
        }
        set_loop(mylist);
    }
}

CodePudding user response:

In case your output looks something like this: 52e922, then you probably just need to do System.out.println(Arrays.toString(s)); in order to print the array correctly.

CodePudding user response:

Your python example creates a mutable list of mutable lists of ints:

def main():
    my_list = [[1, 1, 1], [0, 0, 0], [0, 0, 0]]
    for inner in my_list:
        s = set(inner)
        print(s)


if __name__ == '__main__':
    main()

Output:

{1}
{0}
{0}

To create the same in Java you need to initialize the overall list and add the inner lists to it on separate lines:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {

    public static void main(String[] args) {
        List<List<Integer>> myList = new ArrayList<>();
        myList.add(Arrays.asList(1, 1, 1));
        myList.add(Arrays.asList(0, 0, 0));
        myList.add(Arrays.asList(0, 0, 0));
        for (List<Integer> inner : myList) {
            Set<Integer> s = new HashSet<>(inner);
            System.out.println(s);
        }
    }

}

Java output:

[1]
[0]
[0]
  • Related