array 1 « List « Java Collection Q&A

Java Collection Q&A
3.Array Byte
4.Array Char
5.Array Convert
6.Array Dimension
7.Array Integer
8.Array Object
9.Array String
14.Garbage Collection
Java Collection Q&A » List » array 1 

1. Is there an expandable list of object references in Java?

In Java, we can always use an array to store object reference. Then we have an ArrayList or HashTable which is automatically expandable to store objects. But does anyone know a ...

2. Set Variable from an Array directly into a List of Variables in Java

I have a Java method which returns an array of doubles. I would then like to store these values in individual variables in the calling function. Is there an elegant way ...

3. Convert an array of primitive longs into a List of Longs

This may be a bit of an easy, headdesk sort of question, but my first attempt surprisingly completely failed to work. I wanted to take an array of primitive longs ...

4. How to convert List to int[] in Java?

This is similar to this question: I'm new to Java. How can i convert a List to int[] in Java? I'm confused because List.toArray() actually returns an Object[], which can be ...

5. Should we use type cast for the object.toArray()?

String[] a = c.toArray(new String[0]);
First: Do I need type cast here? (I think we should write like (String[])c.toArray(); BUT I have seen it as just c.toArray() without using type cast. Is ...

6. Odd generics behaviour of List.toArray(T[])

I came across something very basic but extremely bewildering today. I needed to convert a list to an array. The list contained String instances. Perfect example of using List.toArray(T[]), since I ...

7. List to String, can you help refactor this ( small ) method?

We use this small utility method. But we dont like it. Since it's not very crucial ( that work anyway ... ) , we have forget it. But that's ugly, because ...

8. How to generate a random number with Java from given list of numbers

Assume I have an array/vector of numbers like 1,3,7,9 then I need to guess a number from this list randomly. Using Random class in Java it seems like not possible to ...

9. refactoring Java arrays and primitives (double[][]) to Collections and Generics (List>)

I have been refactoring throwaway code which I wrote some years ago in a FORTRAN-like style. Most of the code is now much more organized and readable. However the heart of ...

10. How to use a List of arrays in Java?

I want to declare a List<int[]> or Map<int[],Boolean> but it's very difficult because arrays in Java doesn't implement the equals() method. If two arrays a and b are equal, a.equals(b) returns ...

11. Arrays.asList() not working as it should?

I have a float[] and i would like to get a list with the same elements. I could do the ugly thing of adding them one by one but i wanted ...

12. Working with a List of Lists in Java

I'm a newbie java programmer and having some difficulties with [Array]List. Specifically, I'm trying to read a CSV file into a list of lists (of strings), pass it around for getting ...

13. When to use a List over an Array in Java?

In Java, when would it be preferential to use a List rather than an Array?

14. list of 2D array in java

Hi i have set of 2D arrays and i want store all 2D arrays into single list how can do this in java?

15. Java: convert List to a join()d string

Javascript has Array.join()

js>["Bill","Bob","Steve"].join(" and ")
Bill and Bob and Steve
Does Java have anything like this? I know I can cobble something up myself with StringBuilder:
static public String join(List<String> list, String conjunction)

16. In java to remove an element in an array can you set it to null?

I am trying to make a remove method that works on an array implementation of a list. Can I set the the duplicate element to null to remove it? Assuming that ...

17. Java: Are there some tools out there which are able to refactor X[][] to List>?

I have to refactor an existing project, which is not that small. It contains a lot of arrays declarations and accesses:
(X is not a generic type, it's just a placeholder).
declarations: X[] ...

18. Benchmarking small Arrays vs. Lists in Java: Is my benchmarking code wrong?

Disclaimer: I have looked through this question and this question but they both got derailed by small details and general optimization-is-unnecessary concerns. ...

19. Working with arrays of lists pattern in java

I am writing a card game in java where I need to spread cards from a deck into several columns until I have fixed amount of cards left. This is how ...

20. Java: Is there any short combination to convert array of primitive to List & receive "printable" version?

int[] arrc = new int[] {1, 2, 3};
System.out.println(new ArrayList(Arrays.asList(arrc)));
prints address, but i desire to use toString as in ArrayList. Is it possible ?

21. Why would you use a MyObject[] internally, but expose a List?

I have come across a class that has an immutable property:

MyObject[] allObjs
The property is initialized like this:
List<MyObject> objs = createAllMyObjects();
allObjs = objs.toArray(new MyObject[objs.size()]);
When it is exposed through the accessor, it's done ...

22. Java Collections.rotate() with an array doesn't work

I have the following Java code:

import java.util.Arrays;
import java.util.Collections;

public class Test {
    public static void main(String[] args) {
        int[] test = {1,2,3,4,5};

23. Java: Combine 2 List

I have two List of array string. I want to be able to create a New List (newList) by combining the 2 lists. But it must meet these 3 conditions: 1) Copy ...

24. Java: change an element in a prepopulated List of string array

I have a List of string array already populated in storeInv. How do i change a specific element in the string array? For example the code below... Thanks =]

List <String[]> storeInv ; ...

25. Convert List of one type to Array of another type using Dozer

I'm wondering how to convert a List of one type to an array of another type in Java using Dozer. The two types have all the same property names/types. For example, ...

26. Java : convert List of Bytes to array of bytes

Trying to solve what should be a simple problem. Got a list of Bytes, want to convert it at the end of a function to an array of bytes.

final List<Byte> ...

27. suppose list is an array of six components of the type int. What is stored in list after the following Java code executes?

Suppose list is an array of six components of the type int.What i stored in list after the following Java code executes?

list [0] = 5;

for (i =1; i < 5; i++)

28. Generic List of Array

How remove the:

Type safety: The expression of type List[] needs unchecked conversion to conform to List<Object>[]
compiler warning in the following expression:
List<Object>[] arrayOfList = new List[10];

29. Is having a List and an array with the exact same element bad programming style?

I have a short (12 elements) LinkedList of short strings (7 characters each). I need to search through this list both by index and by content (i.e. search a particular string and ...

30. A more elegant solution to creating an array from comma sep list of properties?

In my properties file I have one property, which contains a comma separated list of values In my code, I would like to load that property in, split it from the commas, ...

31. Most concise way to insert array of bytes into List?

In some code I'm creating a List of Bytes, and want to insert an array of bytes into the list as I am building it. What is the cleanest way ...

32. Converting an int array to a String array

So I have this "list" of ints. It could be a Vector, int[], List<Integer>, whatever. My goal though is to sort the ints and end up with a String[]. ...

33. Array of arrays in Java

So I want to start and say I am new to Java programming. Here is my problem. I want to create a program that in essence cycles through an array of ...

34. Convert Integer List to int array

Is there a way, to convert a List of Integers to Array of ints (not integer). Something like List to int []? Without looping through the list and manually converting the ...

35. java - list question - Why did it print out -4 on the 3rd printout when i ran it?

package javaapplication8;

public class Main {

   public static void main(String[] args) {
     int[] list1 = {1, 2, 3,4};
     int[] list2 = {5, ...

36. Java array initialization list ending with a comma

The comma , items separator used in an array initialization list may end the list in C, this is mentioned in The C Programming Language 2nd ed by Kernighan & Ritchie ...

37. Generating a multiple list of combinations for a number in Java

The following is the problem I'm working on and my snippet of code. Is there a better way to implement this? I have used basic control structures for this below. Is it better ...

38. How to create a List collection staring data in an array?

I was given a task to create an implementation of generic collection basing on simple array. Collection should implement List interface. Currently I have:

import java.util.*;
import java.util.List;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Iterator;

public class Main ...

39. converting an array of bytes to List

I could think of these things,

  1. Arrays.asList(byte[]) converts byte[] to List<byte[]>,
  2. looping through byte array and add each element to list
I was just wondering Is there any library function to do that? ...

40. How do you convert from a List to a primitive array of a different type

How do you convert from a List to an array of a different type (e.g. I would like to go from List<Integer> to double[])

41. Find and list duplicates in an unordered array consisting of 10,000,000,00 elements

How can duplicate elements in an array, that consists of unordered 10,000,000,00 elements, be determined? How can they be listed? Please ensure the performance is taken care of while writing the logic of ...

42. Java array initialization within argument list

How come the first call to someMethod doesn't compile without being explicit that it's String[]? It's fine to use an array initializer to create a String[] array but you can't ...

43. Java Arrays.asList on primitive array type produces unexpected List type

Possible Duplicate:
Arrays.asList() not working as it should?
Apparently the return type of Arrays.asList(new int[] { 1, 2, 3 }); is List<int[]>. This seems totally broken ...

44. proper way to use list to array?

public class TestClass{

private String divisions[] ={};

public void doAction(){

 Collection testArray = new ArrayList();
 // put testArray will data

  divisions = (String [] )  testArray.toArray(division);    //should i ...

46. list of imageIcon

it is possible using a list like

    private LinkedList<Object> deckOfCards = new LinkedList<Object>();
    for (int i = 0; i < 4; i++) {

47. Convert List to int[]

Possible Duplicate:
How to convert List<Integer> to int[] in Java?
What's the easiest way to convert a List to int[]? list.toArray(new int[list.size()]) fails on a typecast error ...

48. Using Java List when array is enough

Is it advisable to use Java Collections List in the cases when you know the size of the list before hand and you can also use array there? Are there any ...

49. Merging lists into a single array with unique elements

I have five lists List<String>. I want to get a single array which contains all elements from those lists, eliminating any repartitions. What could be the best way to do this? `Edit: ...

50. How can I create a List of a custom class with two fields and get output?

I need to make list of a gene sequence in Java and the starting positions of the parts that I care. I use a .txt file as input then search "GT" ...

51. When to use List instead of long[]?

There's something I really don't understand: a lot (see my comment) of people complain that Java isn't really OO because you still have access to primitive and primitive arrays. Some ...

52. How to get sub-Collections form collection Java (Collections, Arrays, List) and keep track of last one returned

public Collection<Comment> getCommentCollection() {
   commentCollection = movie.getCommentCollection();       
   return split((List<Comment>) commentCollection, 4);

public Collection<Comment> split(List<Comment> list, int size){


53. Java - generate Random range of specific numbers without duplication of those numbers - how to?

Sounds simple enough...but I've been plugging away at this, trying to find the one and all solution. For a range of numbers, say 1-12, I want to generate a random sequence within ...

54. Java going through a list?

How would I make java go through a list in order? Example: Im trying to get 2 diff coords but If I make it load 1 then it still needs to load ...

55. Java varags method param list vs. array


public static void foo(String... string_array) { ... }
versus Single array param:
public static void bar(String[] string_array) { ... }
Java 1.6 seems to accept/reject the following:
String[] arr = {"abc", "def", "ghi"};
foo(arr);  ...

56. Can we use index like array index to access List?

I am wondering if we can use index to access List For example List list; list[5] blah....

57. How do I return a sum of all entries in a list

I am working on this NumberList class which represents a list of integers. The NumberList object has just one instance variable values, which is a reference to an array of int ...

58. toArray(new MyObject[size]) vs iterating over list and filling the array

which one of the following methodologies is safe from performance hits, assume that the size of List is large (may be 1,000 objects). i)

List<String> myList = new ArrayList<String>();

for(int i=0; i <=10; i++){

59. How to create a Systematic List in Java?

Hey guys, I'm trying to create a systematic list generator in Java however I've come into slight error. Our example is pizza. Problem: Suppose you have 6 total toppings to make ...

60. How to store 2D Array coordinates in a list in java

Question is kind of hard to ask. I'll try my best to explain it. I have a 2D array that is a grid. This grid has its contents filled with 0 and ...

61. java: convert a list of array into an array of array

I have a list like this:

List<MyObject[]> list= new LinkedList<MyObject[]>();
and on Object like this:
MyObject[][] myMatrix;
How can I assign the "list" to "myMatrix"? I don't want to loop over the list and assign element ...

62. What would be hold some number of Double[] in java?

A List or collection or something other? I would be storing between 10 and 20 Double[]. I would want to add more maybe, retrieve them.

63. Adding a list of user-inputted doubles to an Array

So my program, when instantiated asks the user how many "items" they want. My program then creates two arrays, one for the "item name" and one for the "item price". ...

64. Converting String array to java.util.List

How do i convert String array to java.util.List?

65. Interface method agruments Arrays vs util List

I am writing an interface and and its implementation. The interface has a method like

doSomething(String[] strs, Integer[] ints, String msg);
I declared parameters as arrays simply because it will call to ...

66. Generic List and Generic Array

Possible Duplicate:
What is the easiest alternative to a generic array in Java?
I have the following code:
class B<X>
    public void create()

67. How to get the first elements of object arrays in a list with jxpath?

List alma = new ArrayList();
alma.add(new Object[] { "alma", "korte" });
alma.add(new Object[] { "alma2", "korte2" });
alma.add(new Object[] { "alma3", "korte3" });
JXPathContext context = JXPathContext.newContext(alma);
List result = context.selectNodes("????????");
So basically what should I write ...

68. What is the best way of converting List object to long[] array in java?

Is there any utility method to convert a list of Numerical types to array of primitive type? In other words I am looking for a better solution than this.

private long[] toArray(List<Long> values) ...

69. JAVA Read Integers form a Text File and Work on the Array Lists

I have a text file containing the following content:

0 12
1 15
2 6
3 4
4 3
5 6
6 12
7 8
8 8
9 9
10 13
I want to read these integers from a txt file and save ...

70. Simple adventure game - Beginner Java

I have the following question and am quite uncertain on how to get started. If someone could help, I'd appreciate it. Suppose we are writing a simple adventure game in Java. The ...

71. Parse Text File Line by Line, Skipping Certain Lines

I have a file that looks like this (but is much bigger):

>some text
>some more text
I have been playing around with it in Java for some time and have been able to ...

72. How do I create a List of generic arrays in Java?

I've written a class which accepts a generic type, and I'm trying to create an array list of generic arrays within it. I understand that Java can't create ...

73. list.add("stuff"); crashes

I'm trying to make a simple list. I've got this:

    String valuesArray[] = {"473", "592", "1774", "341", "355", "473", "950", "500", "44", "946.35", "750", "950"};
    List<String> ...

74. Converting array of Objects to array of custom Types

I have a method to build the array for the required type. It works for the primitive types. But when I have array of custom objects it doesn't work. So I ...

75. What is the shortest way to initialize List of strings in java?

I searching for the shortest way (in code) to initialize list of strings and array of strings, i.e. list/array containing "s1", "s2", "s3" string elements.

76. Convert a generic list to an array

I have searched for this, but unfortunately, I don't get the correct answer.

class Helper {
    public static <T> T[] toArray(List<T> list) {

77. Can an Object hold an Array of it's own object

I've have an Object Accounts which has sub Accounts within it. I both have the same structure I need there to be one parent account with 1 to many children associated with. ...

78. What is the best and optimal solution to iterate thought list of array of strings and get its value out?

I have list of array of strings, List <String []>, what is the best optimal approach to get contents of this list of array of strings?

public List<String []> readFromString (String data){

79. Java - Use specific element of a list

My function return a List of string array. how i access/print only the first string array from the list in main().

public class URLReader{
public  List<String[]> functie(String x) throws Exception{
List<String[]> substrList = ...

80. is there a better alternative to List initalization than invoking Arrays.asList?

Is there a better alternative to using Arrays.asList as a List bulk initializer? Of concern is that this one is verbose and involves an extraneous class and method.

List<Double> myList = ...

81. Java - making objects with key/value pairs?

I want to make the following types of objects. This is my higher-level desire that I'd like to figure out in Java: ListObject(key, String): every key corresponds to a String value; ...

82. List and array operations in java

I have list List list = [3,4,5,6] of type long and array String [] array =["3","4","5"] and i want the array containing elements that are not in Array array ,how to ...

83. In java, how do I increase the index of two array(list)s of different sizes at the same time?

I have two ArrayLists in java that have different sizes. ArrayLists 'probs' and 'theDoubles' (sizes 4 and 5 respectively). Array 'dprobs' (Double[5]) is just an Array that copies the values of ...

84. List class's toArray in Java- Why can't I convert a list of "Integer" to an "Integer" array?

I defined List<Integer> stack = new ArrayList<Integer>(); When I'm trying to convert it to an array in the following way:

Integer[] array= stack.toArray();
I get this exception:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: ...

85. How to add array of object to the list

I have an array of object like A[] a; I also have a list of A like List<A> b = new ArrayList<A>(); I am wondering how to add a to b?

86. Printing a list in java

I need to read a number of arrays from a file and print them. My first class handles a menu driven program where the user enters a number to tell ...

87. Array of Generic List

I am playing with Generic and arrays, it seems the following code compiles fine,

ArrayList<Key> a = new ArrayList<Key>();
But the compiler complains about this one,
ArrayList<Key>[] a = new ArrayList<Key>[10];
By reading post in ...

88. Array declaration using lists

So I noticed something. When doing a recursive method on codingbat, I looked at the:

String abc = "abc";
String mod = abc.substring(1);
System.out.println(mod); //prints "bc"
So I thought: Hey, why not have a substring-like method for ...

89. How to write arrays to XML file using Java reflection?

I'm attempting to write a small library which will convert Java objects, through reflection, into XML. I've got the majority of it working, but ran into an error when attempting to ...

90. remove() on List created by Arrays.asList() throws UnsupportedException

I have a collection c1<MyClass> and an array a<MyClass>. I am trying to convert the array to a collection c2 and do c1.removeAll(c2), But this throws UnsupportedOperationException. I found ...

91. Given a list 1, 4, 5,9,2 write a program to find possible combinations of two values where sum = 6

Given array a= [1,4,5,9,2].I need to find/print combinations of two values where sum = 6. My code is as below : (it's O(n^2) and not efficient). Any better solutions -

for(int out=0;out<a.length-1;out++)

92. When to prefer a varargs list to an array?

I'm implementing an API an have a method which you pass a list of paths where the program reads resources from

public void importFrom(String... paths) {

I'm using varargs to make calling the ...

93. How to store 2D Array coordinates in a list (not using list container?)

Firstly I did my homework, I've checked this: How to store 2D Array coordinates in a list in java I have created my own Vector2 class (like XNA). I think if i use list ...

94. Array of lists in Java

In Java, how can I create an array where each element is a list of objects containing a pair of keys. Then given an index of this array, I should be ...

95. Round Robin assignment of an element to a list (or array, or collection) in Java

i need to assign some elements to some lists, preferentially with a round robin way. For example i have 3 List and 11 elements, the result should be 2 list ...

96. Java, how to program my own arrays and lists

Homework. I have to program several different types of binary trees. However, I'm not allowed to use utils such as arrays or collections. It is suggested to build my own array, ...

97. List of Arrays in Java

What is the syntax for making a List of arrays in Java? I have tried the following:

List<int[]> A = new List<int[]>();
and a lot of other things. I need to be able to ...

98. Comparing String array to int list

I have created 2 methods.One to import a file and 2 to get scores for each student by using the data and comparing it against the answer key. Although the methods work fine independantly I have struggled to make them work together.Any suggestions/help? here are the methods. I have tried parsing from data String to int t compare with the answer ...

99. java.util.List method-Object[] toArray(Object[] a)returns same array?

Hi All, I like to know when to use the following java.util.List method Object[] toArray(Object[] a) I was very much confused. The return type is object array and the parameter is object array. then what is the difference. can anyone explain this in detail. for example if i pass a string array i am going to get the same string array ...

100. Lists or arrays

Hey guys I need to display a table showing a list of products, such as product price unit apple 1.00 3 pear 2.00 4 can some one please get me started on this, thanks also i will need to add a method for displaying Total price such as product price unit total apple 1.00 3 3.00 pear 2.00 4 8.00 if ...  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.