2016-04-26 6 views
0

4種類の専用オブジェクトArrayList<String>を持つ「items」というクラスを作成しようとしていますが、アイテムの種類に応じてArrayListsにアイテムを追加するメソッドがあります。リストに項目を追加する方法は、次のコードを持っているArrayList内の新しいオブジェクトのパラメータをチェックする方法は?

private ArrayList<String> itemlistweapons = new ArrayList<String>(); 
private ArrayList<String> itemlistapparel = new ArrayList<String>(); 
private ArrayList<String> itemlistaid = new ArrayList<String>(); 
private ArrayList<String> itemlistmisc = new ArrayList<String>(); 

:4つのArrayListがあり

public void additem(String name, String type){ 
    itemlistweapons.add(new Item(name, type).toString()); 
} 

それは追加項目オブジェクトは、名前を取るコンストラクタとItemと呼ばれる別のクラスから来ていますアイテムの種類と種類。

だから、私が知りたいのですが何を、私は、これは言うことができる方法です。

public void additem(String name, String type){ 
    if //the item added has the type "weapon" 
     itemlistweapons.add(new Item(name, type).toString()); 
    else if //the item added has the type "apparel" 
     itemlistapparel.add(new Item(name, type).toString()); 
    else if //the item added has the type "aid" 
     itemlistaid.add(new Item(name, type).toString()); 
    else if //the item added has the type "misc" 
     itemlistmisc.add(new Item(name, type).toString()); 

私はそれらのコメントの代わりに何を入れますか?

+0

'場合(タイプ== "武器")' ... – theblindprophet

+0

場合( "武器" .equals(タイプ)) –

答えて

2
if ("weapon".equals(type)) { 

注:

  • は、与えられたタイプが多分

  • switch/caseブロック処理できない場合は、IllegalArgumentExceptionをスローする必要がありNullPointerExceptionsが

  • を避けるために、最初の文字列リテラルを置きます良い代替品です

  • List<String>の代わりにList<Item>を使用したい場合があります。 ItemからStringを取得することはできますが、他の方法では困難な場合があります。

  • もしあなたがList<Item>を持っていれば、おそらく4つの別個のリストは必要ありません。すべてを1つのリストにまとめるだけです。武器だけを取得するには、そのタイプを常にフィルタリングすることができます。それはより柔軟になります。

  • 多分種類があるべきenum

関連する問題