0

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);
    }
}
4
  • Don't mix arrays and generics together. Instead of Set<float[]> use Set<List<Float>>. Commented Feb 21, 2022 at 13:25
  • result wasn't a set of the contents of the inner array - so your desired result is just a set of numbers and not a set of arrays? Commented Feb 21, 2022 at 13:27
  • @AlexanderIvanchenko, I wanted a set of the floats inside of the array, but when I print what's in the set, I get the same array I wanted to make a set of. Commented Feb 21, 2022 at 14:31
  • Then Arrays utility class will give you a hand with it. Use Arrays.toString(arr) for that purpose. Commented Feb 21, 2022 at 14:38

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.