I am doing some Junit testing on my code, which is meant to produce an arraylist of n prime numbers. I want to compare the created list to a list of known prime numbers in an array, and to do this I need to insert multiple values into an array in my testing class.
So what I have at the moment is
int knownPrimes[] = new int[50];
I know that I could insert values into this array by typing
knownPrimes[1] = 2;
knownPrimes[2] = 3;
etc etc.
I was just wondering how I would do this all in one big chunk, maybe something like:
knownPrimes[] = {2,3,5,7,9...};
but I am not sure of the syntax and I can't find anything on google. Would anyone be able to help me out please ?
Thanks a lot.
int[] knownPrimes = new int[] {2, 3, 5, 7, 9};
As Peter mentioned, the new int[] can be omitted.
try
int[] knownPrimes = {2,3,5,7,9};
or
int[] knownPrimes;
knownPrimes = new int[] {2,3,5,7,9}
I agree with the solutions posted.
A good book is Thinking in Java, by Bruce Eckel. He covers initialization in Chapter 4, "Initialization and Cleanup," and uses Peter's method. You may buy the latest edition or download an older edition for free.
If the list of knownPrimes is not going to be subclassed, you might want to add the keyword final. If it is class variable and you do not want the value to change after the initialization, you might want to add the keyword static. (I suspect that the list of known primes will be the same throughout the execution of the program.) If you want to access the length of the array, use knownPrimes.length.
Oh, and by the way, 9 should not be in the list of knownPrimes.
Related
I have an sorted array consisting elements (1,1,2,3,3,4). I want to get unique elements from this array and length of the resulting array.
Output array should consists (1,2,3,4) and size = 4.
If you are using Java 8, you can do it in the following way:
Arrays.stream(arr).distinct().toArray();
DEMO
The easiest thing to do here might be to just add your array elements to a sorted set, e.g. TreeSet:
int[] array = new int[] {1, 1, 2, 3, 3, 4};
Set<Integer> set = new TreeSet<>();
for (int num : array) {
set.add(num);
}
This option would make good sense if your code also had a need to work with a set later on at some point.
Is this for homework? If it is, please say so. I'm going to assume it is.
I would traverse the array and use a List to store values that I have already seen. If I come across a value that already appears in my List, I'll skip it. If not, I'll add it. Then I'll convert the list to an array and return it. I'm not going to write it for you because I'm assuming it's homework, but that is the basic idea.
NOTE: If performance is a concern, use a HashMap instead of a List.
What is the advantage of declaring an array using a constant in Java? For example,
private static final int CAPACITY = 2;
private int[] items = new int[CAPACITY];
What is difference between the above code and:
private int[] items = new int[2];
Note: An array's length cannot be changed once it is declared. Why should I use constant then?
Because if the CAPACITY is used somewhere else, and in the future you decide that the CAPACITY should be 4, you don't need to change it everywhere.
improves readability of the code
easier to maintain
Compare:
for(int i=0;i<2;i++)
to
for(int i=0;i<CAPACITY;i++)
Avoid magic numbers in the code when you can.
Many Java classes uses constants, Integer, Character and more classes.
you can use this constant for some other array
to make clear of why is this length like: STUDENTS_MAX_SIZE = 1000
The difference is, if the constant is named in any meaningful name, for example:
private int[] items = new int[DEFAULT_CART_ITEM_AMOUNT];
and/or when the constant is used somewhere else, for example:
for(var i = 0; i < DEFAULT_CART_ITEM_AMOUNT; ++i) doSth();
You can (indeed should) use a constant to replace a number when that number is likely to appear in other places in your code and when it is possible that the value may change in the future.
It can also be used to give semantic meaning to the number.
I understand the question is more of "What is the use of constants?"
keeping code clean
ease of changing the constant during your development
etc.
The main reason is readibility and maintainability . Using numeric literals makes code more difficult to read, understand, and edit.
However, when the intent of the numeric literal is obvious using symbolic constants can impair code readability.
Note that in the case of String litteral (or other Objects), there is a memory overhead when using multiple identical String literal instead of a unique String constant.
You shouldn't usually need a constant for array length, because basically there are two scenarios:
The amount of items to store is known in advance and very straightforward, for example: int[] monthlyRevenues = new int[12]; There are 12 months, it would be silly to do static final int NUMBER_OF_MONTHS = 12;
The amount of items to store is not known in advance, in this case it's probably better to use another collection, like List.
If you ever find yourself setting an array with an explicit length and it isn't immediately apparent why it should be that length, you've got probably some other issues which are not solved by refactoring the length to a constant.
Simple question here -- mostly about APIs.
I want to iterate through an array in random order.
It is easy enough to:
fill a List with the numbers 0 to N
shuffle the List with Collections.shuffle
Use this shuffled list to guide my array iteration.
However, I was wondering if step 1 (generating the list of numbers from 0 to N) exists somewhere in prewritten code.
For instance, could it be a convenience method in guava's XYZ class??
The closest thing in Guava would be
ContiguousSet.create(Range.closedOpen(0, n), DiscreteDomains.integers())
...but, frankly, it is probably more readable just to write the for loop yourself.
Noting specifically your emphasis on 'quick', I can't imagine there'd be much quicker than
List<Integer> = new ArrayList<Integer>(range);
and then iterating and populating each entry. Note that I set the capacity in order to avoid having the list resize under the covers.
You may want to check out the Apache Commons which among many other usefull functions, implement the nextPermutation method in RandomDataGenerator class
This is obviously something much bigger then a method of populating the List or array, but commons are really powerfull libraries, which give much more good methods for mathematical computations.
Java doesn't allow you to auto-populate your values. See this question for the ways to populate an array in java
"Creating an array of numbers without looping?"
If you skip step 1 and just do the shuffeling immediately I think you will have the fastest solution.
int range = 1000;
List<Integer> arr = new ArrayList<Integer>(range);
for(int i=0;i<range;i++) {
arr.add((int)(Math.random()*i), new Integer(i));
}
I'm planning to do a small program that'll display a graph which will be updated a few times per second (maybe 100/200ms or so). The purpose is to plot over 1000 different values in the graph, somewhat like an XY plot.
When the array contains 1000 elements, I'd like to add a new element at the end, and in the process pushing all the other elements one step back. In essence, element 999 would become 998, and 998 would become 997... all the way to the first element, which would simply be thrown away. Does anyone have an example or a good algorithm for doing this, either with regular arrays, Vector, LinkedList or any other method?
My first thought would be to create a new array and copy the elements that I want to keep into the new one, throwing away say the first 100 elements. At this point, I'd add the new 100 elements at the end of the array, and keep repeating this process, but surely there must be a better way of doing this?
What you are asking about is called deque in the algorithmic world, i.e. double ended vector.
That is the class you will need.
Basically deque supports adding and removing elements from both the beginning and the end of the sequence.
EDIT Actually as I read through the documentation I was surprised to see that the sdk implementation of deque does not support direct indexing (I am used to using this structure in C++). So I kept on searching and found this answer, linking to this library, which might be of help for you.
Don't use an Array, the complexity of moving all elements is awful! The Java data structure that's best suited for this task is a Deque, I'd say.
I would keep on reusing the same array, and just restart at the beginning. To make myself more clear, suppose you have your array with elements 1..1000
int[] array = new int[1000];
...
array = {1, 2, ...., 1000 };
If you now have to add element 1001, instead of trying to have an array {2, 3, ..., 1000, 1001}, I would go for an array {1001, 2, 3, ... 1000} and just keep track at which index my array actually starts. This replaces the difficulty of moving all elements by keeping a simple counter to the begin-index. To make it easy for yourself, you can introduce a utility method
private int startIndex = 1;//0 at the start
//I assume we are in the situation with array {1001, 2, 3, ..., 1000 }
public int convertIndex( int index ){
return (index + startIndex) % 1000;
}
I am reviewing someone else's Grails code and I see the following:
Set<Integer> weeks = new ArrayList<Integer>()
It looks like after this line is set, Grails thinks that weeks is a HashSet. I am not well versed in either Java or Grails, and the (java) documentation looks like ArrayList extends List and HashSet extends Set, but that this direct construction wouldn't work. Is this a Grails thing? Thanks.
It's somewhat unusual in Groovy to see new ArrayList<Integer>() since [] works identically and is way less verbose, so I would have written that as Set<Integer> weeks = []. Then it's a bit more clear what's going on - Groovy is converting one collection type to another, with the [] really as a convenient way to create a holder and populate the initial data (if there is any). Since there's no syntactic sugar for collections other than [] for List and [:] you need these conversions.
def weeks = [] as Set is probably the more common syntax. This is also more clear since [] is just temporary and using "as" does the conversion, and more explicitly than just declaring the type on the left side.
You can also use this to convert collections to arrays. You can't use Java syntax to create arrays since it uses braces and looks like a Closure definition, so instead of int[] numbers = new int[] { 1, 2, 3 } you have to do int[] numbers = [1, 2, 3] or def numbers = [1, 2, 3] as int[].