proper way to use list to array? - java

public class TestClass{
private String divisions[] ={};
public void doAction(){
Collection testArray = new ArrayList();
// put testArray will data
divisions = (String [] ) testArray.toArray(division); //should i use this
divisions = (String [] ) testArray.toArray(new String [] {}); //should i use this?
}
}
if i use case 1, and i call doaction multiple time, the division, something will show wrong records
if i use case2, divisions will always show the correct records. is my assumption should use case 2?

Yes, in case 1 you could have a problem with extra items on the end of division. Example: the first time you called doAction and division was set to a certain length then if the next time you called it, it needed less space, there would be extra items that did not get overwritten in the array.
However, case 2 is not all that useful because if the array you pass in (which has a length of zero in your example) is not large enough, ArrayList will just create a new array anyway.

Case 2 is the "more correct" way to use it.
Essentially, you're telling the method what type you would like the resultant array.

Prefer the second one only
divisions = (String [] ) testArray.toArray(new String [] {});

Related

Create an Array from existing array with additional element added

I have a method that takes vararg Array of strings
void count(long delta, String... tags);
I have a predefined array of tags for the most cases
String[] tags = { "foo_tag:Foo",
"bar_tag:Bar",
"baz_tag:Baz"
};
and only one tag to be added to predefined tags in each call "project_id:12345"
So the call of count should look like this:
count(delta, "foo_tag:Foo", "bar_tag:Bar", "baz_tag:Baz", "project_id:12345");
How can I simply create a new array containing my existing one plus additional element just in place of calling the method?
Something like this hypothetical Arrays.append method:
count(delta, Arrays.append(tags, "project_id:12345"));
This is storing statistics operation, not a business logic, so I want this operation to be as fast as possible.
Currently, I have helper method appendTag, but it doesn't look elegant as for me
private String[] appendTag(String[] tags, String s)
{
String[] result = new String[tags.length + 1];
System.arraycopy(tags, 0, result, 0, tags.length);
result[result.length-1] = s;
return result;
}
In java, arrays have a fixed size so it won't be possible to extend an array by appending new elements to it.
You will need to create a new array with a larger size and copy the first one elements into it, then add new elements to it, but it's not dynamic yet.
What I can suggest is to use a Collection maybe an ArrayList you will profit from its built-in methods like .add()
There is no easy way to expand an array by one element and add something new. But if you were working with a list instead, you could easily add a new element and then convert it to an array when calling the method:
String[] tags = { "foo_tag:Foo",
"bar_tag:Bar",
"baz_tag:Baz"
};
List<String> tagList = new ArrayList<String>(Arrays.asList(tags));
tagList.add("project_id:12345");
count(delta, tagList.toArray(new String[0]));
If you think you will have a long term need for this, then perhaps consider changing the implementation of count() to use a list instead of an array. You could also overload this method and expose a version which accepts list instead of array.

Not able to add the values to the list

Hi i am trying to add the values to list as show in below code. i am getting error.
for (String n2 : number ) {
List<String> ARRAY = new ArrayList<String>();
if (!ARRAY.contains(number)) {
ARRAY.add(number);
}}
But getting error while adding the number in to list.
error
java:271: error: no suitable method found for add(List<String>
ARRAY.add(number);
^
method List.add(int,String) is not applicable
(actual and formal argument lists differ in length)
method List.add(String) is not applicable
(actual argument List<String> cannot be converted to String by method invo
if i use like below
for (String n2 : number ) {
List<String> ARRAY = new ArrayList<String>();
if (!ARRAY.contains(n2)) {
Email(n2);
ARRAY.add(n2);
}
}
if i am using above. Though already email sent with value n2 again it is sending again.
For first it has to sent but for second time since it is already in array it should not sent right?
Problem with your code is you are adding number instead of n2
Change the code like this
List<String> ARRAY = new ArrayList<String>();
for (String n2 : number ) {
if (!ARRAY.contains(n2)) {
ARRAY.add(n2);
}
}
1) ARRAY should be outside of your for loop.
2) Replace if (!ARRAY.contains(number)) to if (!ARRAY.contains(n2 )).
Your code need to like this
List<String> ARRAY = new ArrayList<String>();
for (String n2 : number ) {
if (!ARRAY.contains(n2 )) {
ARRAY.add(n2);
}
}
You're trying to add a collection - numbers into a List of Strings.
I am assuming you are trying to add n2 into ARRAY.
ARRAY.add(n2);
I am afraid there is a bit more wrong with your code than just that one error. As has been pointed out many times, you are trying to add an iterable collection of strings, number to your Array rather than n2 which is the iteration variable. If you want to add complete Collection instances you can do so using addAll().
As for the rest, I strongly recommend sticking to the Java naming convention and using lower case names for your variables. This will improve readability as many members of the community stick with that convention. You can find a neat write-up here.
You also seem to, unless your code is highly simplified, make the mistake of declaring an ArrayList inside the scope of a loop. you are instantiating a new ArrayList every time you enter the loop. I am not sure that is what you want to do. Be sure to check your design.
Also, if you simply want to avoid having duplicate values, I would suggest using Set as it performs the check automatically using the hashCode() of each member on insertion to check for collisions. Try doing:
HashSet<String> uniqueSet = new HashSet<>(number);
You should now have a Collection of unique strings.
number is collection of string and you are adding int ARRAY instead add n2
List<String> ARRAY = new ArrayList<String>();
for (String n2 : number ) {
if (!ARRAY.contains(n2)) {
ARRAY.add(n2);
}
}
List<String> ARRAY = new ArrayList<String>();
for (String n2 : number ) {
if (!ARRAY.contains(n2)) {
ARRAY.add(n2);
}
}
List<String> ARRAY = new ArrayList<String>(); //have this out of the thread

Is there a way to use an enhanced for loop to copy an array?

I just started using the enhance for-loop. I want to know if I can use this loop to copy an array. I want to iterate through every element of a certain array and copy it to a new one. It would also be nice to use the enhanced for-loop to instantiate my new array (instead of a typical for-loop). In my current implementation I do know how big I want the array to be, but for future reference I would like to know if I can do this, and if so, how.
My specific plans for what I'm doing might help to answer my question. What I am doing is retrieving a line of text from a text file then calling split( "," ) on that string - this returns an array of Strings. I want to store this array in memory so I can play with it later.
The way I understand the enhanced for-loop to work is that the first value is assigned the current position in the array and the second value is the array that is to be traversed.
I was wondering if there are other formats for for-loops, besides: for ( initialization; termination; iterate ) and for ( Object o : list[] ).
If you want to keep to the enhanced for loop for copying an array, there is one mayor problem: the enhanced for loop doesn't have a counter. Inserting elements into an array however requires a counter. So you could of course do this manually like so:
String[] array = {"A", "Bb", "c", "dD"};
String[] newArray = new String[array.length];
int i=0;
for(String stuff : array) {
newArray[i++] = stuff;
}
This is entirely possible but not really the idea behind the enhanced for loop.
More in line with the intention would be something like this:
String[] array = {"A", "Bb", "c", "dD"};
List<String> list = new ArrayList<String>();
for(String stuff : array) {
list.add(stuff);
}
String[] newArray = new String[list.size()];
list.toArray(newArray);
That way not only do you follow the idea behind the enhanced for loop, you also allow for the possibility that array.length() != newArray.length() (because, say, you filtered the array).
EDIT: as of Java 7, there are indeed only the two for loops you mentioned. This may change in future versions though if it seems sensible; after all, the enhanced for loop was only added in Java 5 (as can be seen here).
To my knowledge, there are only standard for(init; termination; iterataion) loops and for-each for(type o : iterable) loops.
First, knowing the size ahead of time shouldn't be a concern. For instantiating the new array use the original array's .length field: new String[original.length]; as shown below.
Moving along, for what you are doing, the standard for loop is appropriate for two reasons:
You would need to nest two for-each loops in order to iterate both
loops, making it more hassle than a standard for loop. (or add an externally defined counter, as in blalasaadri's solution)
More importantly, in the case of a primitive data type or a String, the variable declared before the : in the for-each loop represents the value of each successive element, and is not a reference to the actual element. As such, any changes to the variable are gone once the loop iterates. I'm not sure if this holds for 'normal' objects (ie: not String), as I've not tried, though I want to find out now.
To illustrate:
String[] sArr = {"foobar"};
for(String s : sArr){
s = "openbar";
}
is the equivalent of:
String[] sArr = {"foobar"};
String s = sArr[0];
s = "openbar";
Sadly, for sArr[0], there is no open bar, same old foobar.
As for solutions, if you can import java.util.Arrays; then try:
String[] copyStrings = Arrays.copyOf(arrStrings, arrStrings.length);
Or, if you need to roll your own:
public String[] copyArray(String[] original){
String[] dupe = new String[original.length]; //I assume you want equal length
for(int i = 0; i < original.length; i++){
dupe[i] = original[i]; //single iterator traverses both arrays
}
return dupe;
}
// copy contents of Object[] arr1 into Object[] arr2
arr2 = new int[arr1.length];
int i=0;
for(Object c:arr1){ //store an element of arr1 in c iteratively
arr2[i] = c;
i++;
}

java multidimensional array declaration 1*3 dimension?

hi i am new to java.After so research about what i am facing, i try post to ask some question.
recently i am doing a text analyse software.
and i try to get done with a 1*3 dimensional array.
something like
[0]
[][][]
[1]
[][][]
[2]
[][][]
[3]
[][][]
the three column in the second dimension of each is use for saving the details of the first dimension.
but the second dimension array size is yet unknown which mean that, idont know how many i will find from the text that i am gonna search.it will increase once the target found.
is this the stupid way for doing this.
i know java can declare array like int [][] abc = new [5][].
but it just can declare only for one unknown dimension.
then i try to do something like this
String [] abc = new string [4]
then i first make a presumption that the size is that in the first column in the second dimension.
abc[0] = String [10][][] inside1;
abc[1] = String [10][][] inside2;
abc[2] = String [10][][] inside3;
abc[3] = String [10][][] inside4;
but still getting error when i compile it.
how can i do the declaration or there got better to done this easy.
if i miss any post in the internet about this. please show me any keyword or link for me to take a look.
What is it that you are trying to implement? Sounds like you instead should use one of the collection classes together with value objects that represent your data.
I think i understand what you are trying to do and its like this:
String[][] value = new String[4][3];
Java doenst have multidimensional arrays, its Arrays Within Arrays.
If you're trying to parse a text file and you know what each column signifies, you should create a new object which contains that data. Arrays of arrays are an unnecessarily painful hack and your code is much more maintainable if you just do what Java is designed to be used for--write a class.
Example for a 10x13 matrix:
String [] [] abd = new String [10] [13];
EDIT: I chose 10x13, because 1x3 doesn't make much sense, being the first value 1.
Why don't you create an Object that has a 'name' property (or 'index' if you prefer), and a 'list' property of type List?
public class YourMultiDimensionalArrayObject {
private int index;
private List<String> vals;
public YourMultiDimensionalArrayObject(int _index) {
index = _index;
}
public void setValues(List<String> _vals) {
vals = _vals;
}
public int getIndex() {
return index;
}
public List<String> getVals() {
return vals;
}
}
You can use ArrayList to store an array of int values of unknown length. You can use an ArrayList> to store an indefinite number of int arrays.
I would create either a List<List<String>> or a Map<String, List<String>>, assuming the values you want to store and look-up by are Strings.

How to convert a List of String arrays to a List of objects

I want to convert a List to a List so that each object on my new list includes the first element of each String[].
Do you know if this is possible to do in java?
for example:
public List<String[]> readFile(){
String[]array1={"A","1.3","2.4","2.3"};
String[]array2={"B","1.43","3.4","2.8"};
String[]array3={"C","5.23","2.45","2.9"};
List<String[]>ReadFile= new ArrayList<String[]>();
ReadFile.add(array1);
ReadFile.add(array2);
ReadFile.add(array3);
return ReadFile;
}
Now I want a method which will take the List ReadFile from above to somehow split the arrays of strings into an ID which will be the first element "A", "B", "C" and another part which would be the string array of numbers which I will put through another method to convert numbers from String to type Double. I have already got the method to convert to double but I need to be able to keep track of the ID field because the ID field will be used to identify the array of numbers.
A friend suggested that I create an Object where each objects has one part as a String ID and the other part as an array. That is the part which I do not know how to do.
Can anybody help please?
below is the method declaration which I believe I should have so the return type will be List where each array has been converted to an Object with two parts.
public List<Object> CreateObject(List<String[]>ReadFile){
}
Thanks,
Jetnori.
Hi all, Thank you for taking your time to help.
I can see the benefit of using HashTables. I am as of now trying to implement it. I know i might be sidetracking a little but just to explain what I am trying to do:
In my project I have CSV file with data about gene expression levels. The method that I use from OpenCSV to read the file returns a List(String[]) where each String[] is one row in the file. The first element of each row is variable name (recA, ybjE etc). The rest of the row will be numbers data related to that variable. I want to calculate Pearson's correlation between each of the number arrays. The method which I have got implemented already does that for me but the problem that I have now is that I had to remove the string values from my arrays before I could convert to double by iterating over the array. After I have managed to calculate the correlation between each array of doubles by still keeping the ID linked to the row, I want to be able to draw an undirected node graph between the genes that have a correlation higher than a threshold which I will set (for example correlation higher than 0.80). I don't know if i am biting more than i can chew but I have 30 days to do it and I believe that with the help of people like you guys I will get through it.
Sorry for going on for a bit.
thanks,
Jetnori.
I agree with the answer Alb provided, however this is what your friend has suggested, first you need a class to represent the data. I have included a constructor that parses the data and one that accepts already parsed data, depending on how you like to think of things.
public class NumberList {
private double[] numbers;
private String key;
public NumberList(Strig key, double[] numbers){
this.ley = key;
this.numbers = numbers;
}
public NumberList(String[] inputList) {
key = inputList[0];
numbers = new double[inputList.length-1];
for(int i=1;i<inputList.length;i++){
numers[i-1] = Double.parseDouble(inputList[i]);
}
}
public String getKey() {
return key;
}
public double[] getNumbers() {
return numbers;
}
}
Then you need your function to generate the list:
public List<NumberList> CreateObject(List<String[]> ReadFile){
ArrayList<NumberList> returnList = new ArrayList<NumberList>(ReadFile.size());
for (String[] input : ReadFile) {
returnList.add(new NumberList(input));
}
return returnList;
}
Note this uses the constructor that parses the data, if you use the other constructor then the "CreateObject" function would need to include the parsing logic.
Finally on a side note the standard convention in java is that the only thing that is capitalized are class names and final static fields (which appear in all caps sepearted by underscores), so conventionally the method signature would be:
public List<NumberList> createObject(List<String[]> readFile){
...
}
Sounds like you need a Map instead of a List, it lets you index things by a key (in your case ID).
Map<String, String[]> map = new Hashmap<String, String[]>();
for( String[] array : ReadFile ){
map.put( array[0], array );
}
then to get the array of values for 'A' you would do:
String[] values = map.get( "a" );
If you want the values to be doubles instead of strings you'll want to change the array before putting it (the map.put call) I'd advise using a list or other collections instead of an array also. You also will probably also want to remove the ID part from these values, which my code does not do.
public class Split_ListwithIDs {
Hashtable<String, String[]> table = new Hashtable<String, String[]>();
Splitter spl ;
public Split_ListwithIDs(Splitter split){
spl = split;
}
private void addEntry(String key , String[] vals){
table.put(key, vals);
}
public void parseList(List<String[]> list){
for(String[] entry : list){
String[] temp = new String[entry.length - 1];
System.arraycopy(entry, 1, temp, 0,entry.length - 1);
addEntry(entry[0], spl.GetStringArrayOfNumbers(temp));
}
}
class SplittingHelper implements Splitter{
#Override
public String[] GetStringArrayOfNumbers(String[] arr) {
String[] strArray = null ;
// implementation here
return arr;
}
}
interface Splitter {
String[] GetStringArrayOfNumbers(String[] arr);
}
}
You will have to use a Hashtable instead of a list of objects.( I am assuming that you will need to search through the list for a given entry using the First alphabet as key - This will be very laborious if you want to use a List ).
In the method SplittingHelper , provide your custom logic to parse the string of numbers and return another string[] of numbers.
I don't understand your goal, but for 'an object with 2 parts' you might consider storing them in a Hashtable: http://download.oracle.com/javase/6/docs/api/java/util/Hashtable.html

Categories

Resources