簡體   English   中英

比較Java數組

[英]Compare Java arrays

我正在嘗試在一個簡單的Java程序中比較房間類型的名稱,但無法正常工作。

到目前為止,我有這個:

public class Main {
public static void main(String[] args) {
    RoomType[] ar = new RoomType[10];
    String s = "";
    String duplicate = "";

    ar[0] = new RoomType("Standaard", 2, 60.0);
    ar[1] = new RoomType("DeLuxe", 2, 85.0);
    ar[2] = new RoomType("DeLuxe", 4, 125.0);
    ar[3] = new RoomType("Hiker", 2, 35.0);

    for (int i = 0; i < ar.length; i++) {
        if (ar[i] != null) {
            s += ar[i] + "\n";
        }

        for (int j = 0; j < ar.length -1; j++) {
            if (ar[i] == ar[j] && ar[i] != null && ar[j] != null) {
                duplicate = ar[i] + " has the same name as " + ar[j];
            }
        }
    }

    System.out.println("These are the roomtypes: \n" + s + "\n");
    System.out.println(duplicate);
}

}

我想比較所有ar[]的名稱(數組中的第一個元素),如果有雙精度型,我需要一個sysout給出雙精度型的位置( ar[] )。 方法getTypeName()在另一個類RoomType中。

“我想比較所有ar []的名稱(數組中的第一個元素),如果有雙精度型,我需要一個sysout給出雙精度型的位置(ar [])”

看來您的方法是錯誤的。 您的RoomType可以根據您的要求實現equalshashcode ,然后可以將其添加到不允許重復的數據結構中,例如java.util.Set 嘗試將重復元素插入到Set中將返回false ,這可以為您提供幫助。 除非您正在使用Java練習/研究數組,否則標准數據結構將為您解決這類問題。

需要注意的幾件事:

  • 使用StringBuilder可以節省更多的空間/時間: http : //docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html “增長”字符串。
  • “ ==”和“!=”通過引用而不是值比較字符串。 使用.equals()代替。
  • 我們可以使用HashMap<String, ArrayList<Integer>>有效地存儲重復信息。 我們將類型名稱映射到數組中的位置。 我在下面編寫了一個函數:

public void printDuplicateInfo(RoomType[] roomList) {

  HashMap<String, ArrayList<Integer>> map = new HashMap<String, ArrayList<Integer>>();
  for(int i = 0; i < roomList.length; i++) {
    ArrayList<Integer> pos;
    String name = roomList[i].getTypeName()
      if(!map.containsKey(name))
        pos = new ArrayList<Integer>();
      else
        pos = map.get(name);
    pos.add(i);
    map.put(name, pos);
  }

  Set<String> keys = map.keySet();
  StringBuilder strBuf = new StringBuilder();
  strBuf.append("***Duplicate Info***\n");
  for(String name : set) {
    ArrayList<Integer> pos = map.get(name);
    int size = pos.size();
    if(size == 1)
      continue;
    strBuf.append(name).append(": present at indices ");
    for(int i = 0; i < size; i++)
      strBuf.append(pos.get(i)).append(" ");

    strBuf.append("\n")
  }

  System.out.print(strBuf);
}

這就是我要解釋的:

for(int i = 0; i < ar.length; i++)
{
  if(ar[i] != null)
    s += ar[i].getTypeName()+"\n";
 for(int j = 1; j < ar.length; j++)
  {
    if(ar[i] != null && ar[j] != null && ar[i].getTypeName().equals(ar[j].getTypeName()))
    {
        duplicate += i+" has the same name as "+j+"\n";
    }
  }
}
System.out.println("These are the roomtypes: \n"+s+"\n");
System.out.println(duplicate);

嘗試使用ArrayList和.Contains進行比較。 這將使您的生活更輕松,並為您介紹Java中的更多數據結構。

祝學校一切順利。 這是一個成長的好地方。 積極點 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM