2017-01-04 7 views
0

配列リストのすべての配列リスト要素を比較する方法を知りたいですか?例えば、私は最大の数字である要素を比較したいと思います。第1要素と第2要素を比較する場合と同様に、第2要素は第3要素と比較します。どうやってするの?ArrayListで最大値を得る方法

List <Product> productList= new ArrayList<>(); 

この変数と比較する方法の例はありますか?

productList.get(i).getPrice() 

ありがとうございます。

+0

*リストを並べ替える必要がありますか? –

+0

は必要ありません、私はarraylistで最大の番号を取得したい –

+0

ええ、あなたの配列をソートし、最初または最後の要素を得る – firegloves

答えて

3

のようないくつかのことを比較します

public int getMax(ArrayList list){ 
    int max = Integer.MIN_VALUE; 
    for(int i=0; i<list.size(); i++){ 
     if(list.get(i) > max){ 
      max = list.get(i); 
     } 
    } 
    return max; 
} 

を、より良い方法は、比較器である:ちょうどその

public class compareProduct implements Comparator<Product> { 
    public int compare(Product a, Product b) { 
     if (a.getPrice() > b.getPrice()) 
      return -1; // highest value first 
     if (a.getPrice() == b.Price()) 
      return 0; 
     return 1; 
    } 
} 

とこれを行う:

製品p = Collections.max(製品、新しいcompareProduct());

+0

をどうやってやりますか... –

0

あなただけの最大値は、この使用する場合は、この

for (int i = 0; i < productList.size(); i++) { 

    for (int j = i+1; j < productList.size(); j++) { 

    // compare productList.get(i) and productList.get(j) 

    } 
} 
+0

内側のループを使用する理由?あなたは 'productList.get(i)'と 'max'を比較することができます –

+0

あなたはあなたの答えのためにスニペットコード –

関連する問題