2017-02-23 4 views
0

実際には、キーの位置を指定するたびにLinkedHashMapのキーセットの新しいArrayListを作成します。arraylistでハッシュマップキーセットにアクセスする方法

public static Map<Integer, Object> ObjectsWithId = new LinkedHashMap<>(); 


public int getId(int number) { 
    return (number <= ObjectsWithId.size()) ? new ArrayList<Integer>(ObjectsWithId.keySet()).get(number-1) : -1; 
} 

HashMapのキーセットとArrayListの「リンク」を作成する方法はありますか? キーの位置を求めるたびにArrayListを作成する必要はありません。事前に

public static Map<Integer, Object> ObjectsWithId = new LinkedHashMap<>(); 
public static ArrayList<Integer> ObjectsKeys = new ArrayList<Integer>(ObjectsWithId.keySet()); 

public int getId(int number) { 
     return (number <= ObjectsWithId.size()) ? ObjectsKeys.get(number-1) : -1; 
} 

感謝を:ここで

は、私が試したものを、私は持っていたいと思うものです。 :)

答えて

0

作成したオブジェクトのモチベーションが軽い場合は、配列の作成を検討することができます。

public int getId(int index) { 
    return (index <= ObjectsWithId.size()) ? (int) ObjectsWithId.keySet().toArray()[index-1] : -1; 
} 

ところで:これはあるようインデックスパラメータの名前を変更を検討あなたの意図(私は推測)でした。

0

forループの使用はいかがですか?

ArrayListを作成したくない場合は、以下のように試してみてください。

public int getId(int number) { 
    int position = 0; 
    int i = 0; 

    for (Map.Entry<Integer, Object> entry : ObjectsWithId.entrySet()) { 
     if (number == entry.getKey()) { 
      position = i; 

      break; 
     } else { 
      i++; 
     } 
    } 
    return position; 
} 
関連する問題