Search code examples
javaarraysalgorithmredundancy

Display elements without redundancy in an array


I made this code. I think it is wrong.

public void display() {
    for (int i = 0; i < tabT.length; i++)
        if (tabT[i] != null)
            for (int j = 0; j <= i; j++)
                if (tabT[i] != tabT[j])
                    System.out.println(tabT[i].getCar());
}

How do I display elements without redundancy in an array?


Solution

  • If you want to use only arrays, you can do something like this:

    Make an temp (helper) array, which will include each element seen so far in tabT. Then, before printing the value, you check if it's not appearing in the helper array (tmp).

    For example, if you have values in tabT, and you don't want to print each one more than once:

    int[] tabT = {1,2,3,1,1,2,6,7,2,7,1};
    int[] tmp = new int[tabT.length];
    boolean flag;
    for (int i = 0; i < tabT.length; i++) {
        tmp[i] = tabT[i];
        flag = true;
        for (int j = 0; j < tmp.length; j++)
            if (tabT[i] == tmp[j] && i!=j) {
                flag = false;
            }
        if(flag)
            System.out.println(tabT[i]);
    }
    

    Output: [1,2,3,6,7]

    You can easily apply this idea to your program, and you'll have each element printed only once:

    Cars[] tmp = new Cars[tabT.length]; //Assuming tabT is from type Cars[]
    boolean flag = true;
    for (int i = 0; i < tabT.length; i++) { 
        tmp[i] = tabT[i];
        if (tabT[i] != null) {
            for (int j = 0; j < tmp.length; j++)
                if (tabT[i].getCar().equals(tabT[j].getCar()) && i!=j)
                    flag = false;
            if(flag)
                System.out.println(tabT[i].getCar());
        }
    }
    

    This will print each car (or whatever you're printing) only once.