2

I need to write a method using an ArrayList but I can't quite figure out how to do it.

I was able to do it with just using an array and I was wondering if there was an easy way to change it so that it does implement an ArrayList.

Here is my current code:

//public ArrayList<Integer> getPixelsInWindow(int wSize, int x, int y) { //ArrayList<Integer> values = new ArrayList<Integer>(); public int[] getPixelsInWindow(int wSize, int x, int y) { int [] values; int xMin = 0; int xMax = 0; int yMin = 0; int yMax = 0; xMin = x - (wSize / 2); if (xMin < 0) xMin = 0; yMin = y - (wSize / 2); if (yMin < 0) yMin = 0; xMax = x + (wSize / 2); if (xMax >= rowN) xMax = rowN - 1; yMax = y + (wSize / 2); if (yMax >= columnN) yMax = columnN - 1; int differenceX = xMax-xMin; int differenceY = yMax-yMin; values = new int[(differenceX + 1) * (differenceY + 1)]; int j = 0; for(int i = xMin;i < xMax + 1;i++){ for(int k = yMin;k < yMax + 1;k++){ values[j] = img[i][k]; if(j == 0){ } j++; } } return values; } 
2
  • Why do you need to use an ArrayList?
    – Bernard
    CommentedFeb 1, 2012 at 15:00
  • Where you assign the into values instead do list.add(Integer)CommentedFeb 1, 2012 at 15:05

1 Answer 1

6

This was done quickly and not tested... but the idea is there, I am sure:

... List<Integer> values = new ArrayList<Integer>(); int j = 0; for(int i = xMin;i < xMax + 1;i++){ for(int k = yMin;k < yMax + 1;k++){ values.add(new Integer(img[i][k])); ... } } 
1
  • 4
    Instead of "new Integer" I would use Integer.valueOf(...) which is the preferred way according to SUN practices (better in terms of memory management), or let auto-boxing do it for you. Also, no need for variable j anymore. But still +1
    – Guillaume
    CommentedFeb 1, 2012 at 15:07

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.