2017-10-11 36 views
1

我是Android新手,今天我覺得很有動力,所以我開始編寫一個應用程序。刪除和縮小ArrayList

但現在我卡住了......我有一個ArrayList與字符串在裏面。隨着隨機數發生器,我從這個列表中獲得一個字符串。 我真正想要做的是避免重複字符串。我只想看到一個元素。

你們能幫我嗎?

這裏是我的MainActivity:

public class MainActivity extends AppCompatActivity { 

private TextView welcomeText; 
private TextView pokemons; 
private TextView whatToDo; 
private Button yesButton; 
private Button noButton; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    final String[] pokemonok = { 
      "Pikachu", 
      "Charizard", 
      "Bulbasaur", 
      "Charmander", 
      "Squirtle", 
      "Caterpie", 
      "Metapod", 
      "Weedle", 
      "Rattata", 
      "Onix" 
    }; 

    final List<String> list = new ArrayList<String>(pokemonok.length); 
    for (String s : pokemonok) { 
     list.add(s); 
    } 

    welcomeText = (TextView) findViewById(R.id.welcomeText); 
    pokemons = (TextView) findViewById(R.id.pokemons); 
    whatToDo = (TextView) findViewById(R.id.whatToDo); 
    //EditText answerText = (EditText) findViewById(R.id.answerText); 
    yesButton = (Button) findViewById(R.id.yesButton); 
    noButton = (Button) findViewById(R.id.noButton); 

    final String[] def = {"[ " + list.get(0) + " ]"}; 
    pokemons.setText(def[0]); 

    View.OnClickListener igen = new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 

      Random r = new Random(); 
      int szam = r.nextInt(pokemonok.length); 

      pokemons.setText(def[0] + "[ " + list.get(szam) + " ]"); 
      def[0] = def[0] + "[ " + list.get(szam) + " ]"; 

     } 
    }; 

    yesButton.setOnClickListener(igen); 

    } 
} 
+0

所以要挑選每一次口袋妖怪? –

回答

1

如果你想保留這個列表,你可以有另一個列表,每當你閱讀從原來的列表中的對象,該元素添加到臨時列表。然後,只要你想選擇一個新的隨機元素,首先你必須檢查該元素是否已經在臨時列表中。如果是,則必須重新生成該過程。

List<String> tempList = new ArrayList<>(); 
tempList.add(// YOUR ELEMENT TO SAVE ON TEMP LIST //); 

然後檢查

if (tempList.contains(element)){ 
     // your code to doing the process again 
{ 
1

取決於你如何設置的隨機數,生成器,你可以做這樣的事情:

list.remove(randomNumber); 

這應該從列表中刪除的項目。

2

如果要訪問它之後,從列表中刪除元素,你可以叫

list.remove(i) 

這將從列表中刪除第i個元素。

0

如果你不想改變你的寵物小精靈字符串列表,那麼你可以創建你的類布爾值,其識別口袋妖怪已經採摘的數組:

private boolean[] pokemonPicked = new boolean[pokemonok.length]; 

,你可以改變你的clickListener方法爲此:

View.OnClickListener igen = new View.OnClickListener() { 
    @Override 
    public void onClick(View view) { 

     int r = new Random().nextInt(pokemonok.length); 
     while(pokemonPicked[r]){ 
      r = new Random().nextInt(pokemonok.length); 
     } 
     pokemonPicked[r] = true; 
     int szam = r; 

     pokemons.setText(def[0] + "[ " + list.get(szam) + " ]"); 
     def[0] = def[0] + "[ " + list.get(szam) + " ]"; 

    } 
}; 
+0

這似乎效率低下;在等待有效號碼被選中時,你可能會有任意的延遲。 –

+0

我不會推薦它這樣做,但實際上這個工作比較好,因爲隨機數是平均分佈的。在最壞的情況下,這當然可能會出錯 –

+0

那麼,對於這個相對較低的數字,它可能是好的。如果你爲大量的寵物小精靈(比如數百萬人)這樣做,它最終會成爲一個問題。 –