简体   繁体   中英

Removing Objects from an ArrayList

Hi I am a bit new to Java and Android. I am working on a project which it cycles through random Activities and I am stuck with a problem for days.

public class ActivityHelper extends Activity {
    ArrayList<String> classes = new ArrayList<String>();
    public   void addClass (){
        classes.add("Activity1");
        classes.add("Activity2");
        classes.add("Activity3");
                //etc

    }
    public  String openClass (){
        addClass();
        Random rand = new Random ();
        int crazy = rand.nextInt(classes.size());
        String cheese = classes.get(crazy);
        classes.remove(cheese);
        return cheese;  
    }   
}

// A Method in Activity1 extends ActivityHelper
public void doJob() {

    String cheese = openClass();
    try {               
        @SuppressWarnings("rawtypes")
        Class ourClass = Class.forName("com.activity.dan." + cheese);
        Intent ourIntent = new Intent(Activity1.this, ourClass);
        startActivity(ourIntent);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

The program perfectly cycles through the classes but my problem is the classes.remove(cheese); doesnt work. I am hoping once the Class is opened it will be removed from the ArrayList and wont be used again if the doJob(); method is called on another class. I tried using static and putting the remove list in the Activity1 but nothing seems to work. Your help will be appreciated.

I guess your remove is working but each Activity you create contains a new instance of classes and that's not what you want. It might work this way.

public class ActivityHelper extends Activity{
static ArrayList<String> classes = new ArrayList<String>();
static {
    classes.add("Activity1");
    classes.add("Activity2");
    classes.add("Activity3");
            //etc
}
public  String openClass (){
    // don't add classes here - would be done every time.
    // print out some debug
    Log.d("ActivityHelper", "State before openClass: " + Arrays.toString(classes.toArray()));
    Random rand = new Random ();
    int crazy = rand.nextInt(classes.size());
    String cheese = classes.get(crazy);
    classes.remove(crazy);
    // print out some debug
    Log.d("ActivityHelper", "State after openClass: " + Arrays.toString(classes.toArray()));
    return cheese;
} 

ArrayList.remove() expects an Integer, not a class. Call .remove() with the Integer index you want to remove and it should work as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM