L
Luc The Perverse
Hi - I was wondering if the later java versions (1.5 and higher) allow me to
do something to avoid this silliness.
This happens all the time. I am trying to make a list of integers - and I
don't start out knowing how many there are going to be (although typically I
would know a max). At the end, I know how many there are, and I need to
remake my result to generate an array of the correct size. Here is an
example from a top coder problem in which I use a linked List
import java.lang.*;
import java.util.*;
public class InterestingDigits{
public int[] digits(int base){
boolean bad = false;
LinkedList<Integer> li = new LinkedList<Integer>();
for(int i=2;i<base;i++){
bad = false;
for(int j=i + i;j<base*base*base&&!bad;j+=i){
int s = 0;
for(int c=j;c>0;c/=base)
s+=c%base;
if(s%i!=0)
bad=true;
}
if(!bad)
li.add(new Integer(i));
}
int c = 0;
int[] ret = new int[li.size()];
for(Integer i : li)
ret[c++] = i.intValue();
return ret;
}
}
Those last four lines before the return statement are what I have an
objection to.
Is there a function for returning an array subset that I could directly on
an array of type int[] ? Is there a way to cast directly to an int[] from
a linked list (or any collection) ? (Note: I realize that I can generate
an array of type Integer[] easily enough from a collection using
li.toArray(new Integer[0]) but I would need an int[] )
do something to avoid this silliness.
This happens all the time. I am trying to make a list of integers - and I
don't start out knowing how many there are going to be (although typically I
would know a max). At the end, I know how many there are, and I need to
remake my result to generate an array of the correct size. Here is an
example from a top coder problem in which I use a linked List
import java.lang.*;
import java.util.*;
public class InterestingDigits{
public int[] digits(int base){
boolean bad = false;
LinkedList<Integer> li = new LinkedList<Integer>();
for(int i=2;i<base;i++){
bad = false;
for(int j=i + i;j<base*base*base&&!bad;j+=i){
int s = 0;
for(int c=j;c>0;c/=base)
s+=c%base;
if(s%i!=0)
bad=true;
}
if(!bad)
li.add(new Integer(i));
}
int c = 0;
int[] ret = new int[li.size()];
for(Integer i : li)
ret[c++] = i.intValue();
return ret;
}
}
Those last four lines before the return statement are what I have an
objection to.
Is there a function for returning an array subset that I could directly on
an array of type int[] ? Is there a way to cast directly to an int[] from
a linked list (or any collection) ? (Note: I realize that I can generate
an array of type Integer[] easily enough from a collection using
li.toArray(new Integer[0]) but I would need an int[] )