Skip to content
Advertisement

Tag: arrays

Comparing arrays in JUnit assertions, concise built-in way?

Is there a concise, built-in way to do equals assertions on two like-typed arrays in JUnit? By default (at least in JUnit 4) it seems to do an instance compare on the array object itself. EG, doesn’t work: Of course, I can do it manually with: ..but is there a better way? Answer Use org.junit.Assert’s method assertArrayEquals: If this method

Immutable array in Java

Is there an immutable alternative to the primitive arrays in Java? Making a primitive array final doesn’t actually prevent one from doing something like I want the elements of the array to be unchangeable. Answer Not with primitive arrays. You’ll need to use a List or some other data structure:

How to add new elements to an array?

I have the following code: Those two appends are not compiling. How would that work correctly? Answer The size of an array can’t be modified. If you want a bigger array you have to instantiate a new one. A better solution would be to use an ArrayList which can grow as you need it. The method ArrayList.toArray( T[] a )

Creating a New Reverse Java Array

CodingBat > Java > Array-1 > reverse3: Given an array of ints length 3, return a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}. I can’t get this to work properly, usually the last int in the array, becomes every single int in the new array Answer You don’t want a two-level

Advertisement