简体   繁体   中英

Can not add elements to ArrayList<Integer>

So I am trying to create a ArrayList of Integers and then iterate variables into it. Only the first value that I specify is being added.

 private ArrayList<Integer> heights(String detail) {
        ArrayList<Integer> heights = new ArrayList<Integer>();
        heights.add(0);
        switch(detail) {
            case "L": for(Integer i = 100; i <= 1000; i=+50) { heights.add(i); } break;
            case "H": for(Integer i = 100; i <= 1000; i=+25) { heights.add(i); } break;
        }
        return heights;
    }

Value of heights("H"):

heights: [0]

The Problem is in for loop. Use int instead of Integer class....

The code below works properly...

import java.util.*;  
class Test{
        private ArrayList<Integer> heights(String detail) {
            ArrayList<Integer> heights = new ArrayList<Integer>();
            heights.add(0);
            switch(detail) {
                case "L": for(int i = 100; i <= 1000; i=i+50) { heights.add(i); } break;
                case "H": for(int i = 100; i <= 1000; i=i+25) { heights.add(i); } break;
            }
            return heights;
        }
     public static void main(String args[]){
            Test t = new Test();
            System.out.println(t.heights("H"));
         }
    } 

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