简体   繁体   English

Java比较2D数组与arrayList内部的2D数组

[英]Java comparing 2d arrays to 2d arrays inside arrayList

I am having problems checking if the arrays inside one array are the same as my arrays in a list. 我在检查一个数组中的数组是否与列表中的数组相同时遇到问题。 This is the problem code, it does not seem to stop duplicates from being added. 这是问题代码,它似乎并没有阻止添加重复项。 Arrays.equals() doesn't seem to work either: Arrays.equals()似乎也不起作用:

if(!uniqueTiles.contains(playerPositions[i])) {
    uniqueTiles.add(playerPositions[i]);
}

Here is the entire method so far: 这是到目前为止的整个方法:

// gets the area in fishZone that the bot should walk to, based on the positions 
    // of clusters of players

    List<Player> players = getPlayers().getAll();



    int validPlayerCount = 0;

    // count valid players
    for (int i = 0; i < players.size(); i++) {
        if((players.get(i).getName() != myPlayer().getName()) && fishingZone.contains(players.get(i))) {
            validPlayerCount++;
        }
    }

    int[][] playerPositions = new int[validPlayerCount][2];
    List<int[]> uniqueTiles = new ArrayList<int[]>();

    // put the x and y coordinates of all nearby valid players into a 2d array
    for (int i = 0; i < validPlayerCount; i++) {
            playerPositions[i][0] = players.get(i).getX();
            playerPositions[i][1] = players.get(i).getY();



            if(!uniqueTiles.contains(playerPositions[i])) {
                uniqueTiles.add(playerPositions[i]);
            }
    }

As you can see uniqueTiles is an arrayList because it needs a flexible size, and playerPositions is a 2d array. 如您所见,uniqueTiles是arrayList,因为它需要灵活的大小,而playerPositions是2d数组。

Do not use List s if you don't want duplicates: 如果您不想重复,请不要使用List

Unlike sets, lists typically allow duplicate elements. 与集合不同,列表通常允许重复的元素。

In Java, object comparison is made using the methods equals and hashCode . 在Java中,使用equalshashCode方法进行对象比较。 You can use third party libraries such as Apache Commons Lang's EqualsBuilder and HashCodeBuilder to help you implementing those. 您可以使用第三方库(例如Apache Commons Lang的EqualsBuilder和HashCodeBuilder)来帮助您实现这些库。

Look at the source code of List.contains if you're curious. 如果您好奇的话,请查看List.contains的源代码。

Try this method : 试试这个方法:

TreeSet<Integer[]> set = new TreeSet<>((o1, o2) -> Arrays.deepEquals(o1, o2) ? 0 : 1);
    set.add(new Integer[]{1, 2, 4});
    set.add(new Integer[]{1, 2, 4});
    set.add(new Integer[]{1, 2, 4});
    System.out.println(set);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM