if i don't know array will be have how many elements? - java

I want to give an example.
import java.util.Scanner;
public class ana
{
public static void main(String[] args) {
int[] array = new int[9]; // create array that have "9" elements
}
}
Above example's array have 9 elements but i want to create unlimited array.
If I want this when I'm writing PHP I write this code:
<?php
$example = array();
$example[] = 15; // auto numbering. PHP don't want number of array's element.
$example[] = 20;
?>
And what does mean?
Auto[] array = {new Auto()};
I hope I made myself clear.

Use a List (such as an ArrayList). Java has a number of collections (List, Set, Map, Queue, etc.), with various implementations. Learn how to use them by reading the collections tutorial.

You need to use a different data structure, like a Vector.

Try using ArrayList, resizable-array implementation of the List interface in Java.

Use ArrayList in java.
ArrayList<Integer> array = new ArrayList<Integer>();

I think you need an ArrayList:
ArrayList<Integer> as = new ArrayList<Integer>();
as.add(15);
as.add(20);
and Auto[] array = {new Auto()}; is a Array of Type Auto with one element.

Related

Multi-dimensional Java ArrayList (Declared element syntax)

Is it possible to do the following?
private static ArrayList<integer<integer<String>>> myArrayList;
In other words, create an ArrayList with declared element syntax?
Example:
myArrayList[0][0] = "This is the string.";
If not, is it possible to do such with normal arrays?
It seems you are looking for multi-dimensional arrays in Java, declared as follows:
String [][] list = new String[10][10];
list[0][0] = "This is a string";
System.out.println(list[0][0]);
You can declare List of List in the following way: -
List<List<String>> listOfList = new ArrayList<List<String>>();
Initialize your List, and then to add a String to your list element: -
listOfList.add(new ArrayList<String>());
listOfList.get(0).add("my String");
You can do
List<List<String>> list = new ArrayList<List<String>>();
list.add(new ArrayList<String>());
list.get(0).add("This is the string");
What you would want to achieve in realtime?, Java defines set of APIs, which has its own usage and purpose. If you want to use multidimensional array, I would suggest to go for Object[][], though you should be able to declare
ArrayList list[][] = new ArrayList[5][7];
By doing so, you would be making you operation bit complex. And more over ArrayList is nothing but single dimensional Object array.
FYI
How to create a Multidimensional ArrayList in Java?

Convert list to array in Java [duplicate]

This question already has answers here:
Converting 'ArrayList<String> to 'String[]' in Java
(17 answers)
Closed 4 years ago.
How can I convert a List to an Array in Java?
Check the code below:
ArrayList<Tienda> tiendas;
List<Tienda> tiendasList;
tiendas = new ArrayList<Tienda>();
Resources res = this.getBaseContext().getResources();
XMLParser saxparser = new XMLParser(marca,res);
tiendasList = saxparser.parse(marca,res);
tiendas = tiendasList.toArray();
this.adaptador = new adaptadorMarca(this, R.layout.filamarca, tiendas);
setListAdapter(this.adaptador);
I need to populate the array tiendas with the values of tiendasList.
Either:
Foo[] array = list.toArray(new Foo[0]);
or:
Foo[] array = new Foo[list.size()];
list.toArray(array); // fill the array
Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way:
List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);
Update:
It is recommended now to use list.toArray(new Foo[0]);, not list.toArray(new Foo[list.size()]);.
From JetBrains Intellij Idea inspection:
There are two styles to convert a collection to an array: either using
a pre-sized array (like c.toArray(new String[c.size()])) or
using an empty array (like c.toArray(new String[0]). In
older Java versions using pre-sized array was recommended, as the
reflection call which is necessary to create an array of proper size
was quite slow. However since late updates of OpenJDK 6 this call
was intrinsified, making the performance of the empty array version
the same and sometimes even better, compared to the pre-sized
version. Also passing pre-sized array is dangerous for a concurrent or
synchronized collection as a data race is possible between the
size and toArray call which may result in extra nulls
at the end of the array, if the collection was concurrently shrunk
during the operation. This inspection allows to follow the
uniform style: either using an empty array (which is recommended in
modern Java) or using a pre-sized array (which might be faster in
older Java versions or non-HotSpot based JVMs).
An alternative in Java 8:
String[] strings = list.stream().toArray(String[]::new);
Since Java 11:
String[] strings = list.toArray(String[]::new);
I think this is the simplest way:
Foo[] array = list.toArray(new Foo[0]);
Best thing I came up without Java 8 was:
public static <T> T[] toArray(List<T> list, Class<T> objectClass) {
if (list == null) {
return null;
}
T[] listAsArray = (T[]) Array.newInstance(objectClass, list.size());
list.toArray(listAsArray);
return listAsArray;
}
If anyone has a better way to do this, please share :)
I came across this code snippet that solves it.
//Creating a sample ArrayList
List<Long> list = new ArrayList<Long>();
//Adding some long type values
list.add(100l);
list.add(200l);
list.add(300l);
//Converting the ArrayList to a Long
Long[] array = (Long[]) list.toArray(new Long[list.size()]);
//Printing the results
System.out.println(array[0] + " " + array[1] + " " + array[2]);
The conversion works as follows:
It creates a new Long array, with the size of the original list
It converts the original ArrayList to an array using the newly created one
It casts that array into a Long array (Long[]), which I appropriately named 'array'
This is works. Kind of.
public static Object[] toArray(List<?> a) {
Object[] arr = new Object[a.size()];
for (int i = 0; i < a.size(); i++)
arr[i] = a.get(i);
return arr;
}
Then the main method.
public static void main(String[] args) {
List<String> list = new ArrayList<String>() {{
add("hello");
add("world");
}};
Object[] arr = toArray(list);
System.out.println(arr[0]);
}
For ArrayList the following works:
ArrayList<Foo> list = new ArrayList<Foo>();
//... add values
Foo[] resultArray = new Foo[list.size()];
resultArray = list.toArray(resultArray);
Example taken from this page: http://www.java-examples.com/copy-all-elements-java-arraylist-object-array-example
import java.util.ArrayList;
public class CopyElementsOfArrayListToArrayExample {
public static void main(String[] args) {
//create an ArrayList object
ArrayList arrayList = new ArrayList();
//Add elements to ArrayList
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
/*
To copy all elements of java ArrayList object into array use
Object[] toArray() method.
*/
Object[] objArray = arrayList.toArray();
//display contents of Object array
System.out.println("ArrayList elements are copied into an Array.
Now Array Contains..");
for(int index=0; index < objArray.length ; index++)
System.out.println(objArray[index]);
}
}
/*
Output would be
ArrayList elements are copied into an Array. Now Array Contains..
1
2
3
4
5
You can use toArray() api as follows,
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("ListItem1");
stringList.add("ListItem2");
String[] stringArray = new String[stringList.size()];
stringArray = stringList.toArray(stringList);
Values from the array are,
for(String value : stringList)
{
System.out.println(value);
}
This (Ondrej's answer):
Foo[] array = list.toArray(new Foo[0]);
Is the most common idiom I see. Those who are suggesting that you use the actual list size instead of "0" are misunderstanding what's happening here. The toArray call does not care about the size or contents of the given array - it only needs its type. It would have been better if it took an actual Type in which case "Foo.class" would have been a lot clearer. Yes, this idiom generates a dummy object, but including the list size just means that you generate a larger dummy object. Again, the object is not used in any way; it's only the type that's needed.
Try this:
List list = new ArrayList();
list.add("Apple");
list.add("Banana");
Object[] ol = list.toArray();

Remove a specific string from an array of string

I have an array like this:
String n[] = {"google","microsoft","apple"};
What I want to do is to remove "apple".
My problem is very basic,however,I searched the website and I found out that java doesn't really support the deleting feature from an array.I also heard to use Java Utils, because it's so simple to remove an item....I tried to find Java Utils on google, but almost all links are dead.
So finally...is there any way to remove a string from an array of string?
Even if I use an ArrayList I can't find a method to generate a random item in it! For ex: in a normal array I generate a string like this:
String r = myAL[rgenerator.nextInt(myAL.length)];
In an arraylist it doesn't work....maybe you know a solution...
Define "remove".
Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;
for (int i = 0; i < myStringArray.length(); i++)
{
if (myStringArray[i].equals(stringToRemove))
{
myStringArray[i] = null;
break;
}
}
or
myStringArray[indexOfStringToRemove] = null;
If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>
myArrayList.remove(stringToRemove);
or
myArrayList.remove(indexOfStringToRemove);
Edit in response to OP's edit to his question and comment below
String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
It is not possible in on step or you need to keep the reference to the array.
If you can change the reference this can help:
String[] n = new String[]{"google","microsoft","apple"};
final List<String> list = new ArrayList<String>();
Collections.addAll(list, n);
list.remove("apple");
n = list.toArray(new String[list.size()]);
I not recommend the following but if you worry about performance:
String[] n = new String[]{"google","microsoft","apple"};
final String[] n2 = new String[2];
System.arraycopy(n, 0, n2, 0, n2.length);
for (int i = 0, j = 0; i < n.length; i++)
{
if (!n[i].equals("apple"))
{
n2[j] = n[i];
j++;
}
}
I not recommend it because the code is a lot more difficult to read and maintain.
Arrays in Java aren't dynamic, like collection classes. If you want a true collection that supports dynamic addition and deletion, use ArrayList<>. If you still want to live with vanilla arrays, find the index of string, construct a new array with size one less than the original, and use System.arraycopy() to copy the elements before and after. Or write a copy loop with skip by hand, on small arrays the difference will be negligible.
You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.
You'd be better off with a List<String>, e.g. an ArrayList<String>:
List<String> list = new ArrayList<String>();
list.add("google");
list.add("microsoft");
list.add("apple");
System.out.println(list.size()); // 3
list.remove("apple");
System.out.println(list.size()); // 2
Collections like this are generally much more flexible than working with arrays directly.
EDIT: For removal:
void removeRandomElement(List<?> list, Random random)
{
int index = random.nextInt(list.size());
list.remove(index);
}
import java.util.*;
class Array {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("google");
al.add("microsoft");
al.add("apple");
System.out.println(al);
//i only remove the apple//
al.remove(2);
System.out.println(al);
}
}

From Arraylist to Array

I want to know if it is safe/advisable to convert from ArrayList to Array?
I have a text file with each line a string:
1236
1233
4566
4568
....
I want to read them into array list and then i convert it to Array. Is it advisable/legal to do that?
thanks
Yes it is safe to convert an ArrayList to an Array. Whether it is a good idea depends on your intended use. Do you need the operations that ArrayList provides? If so, keep it an ArrayList. Else convert away!
ArrayList<Integer> foo = new ArrayList<Integer>();
foo.add(1);
foo.add(1);
foo.add(2);
foo.add(3);
foo.add(5);
Integer[] bar = foo.toArray(new Integer[foo.size()]);
System.out.println("bar.length = " + bar.length);
outputs
bar.length = 5
This is the best way (IMHO).
List<String> myArrayList = new ArrayList<String>();
//.....
String[] myArray = myArrayList.toArray(new String[myArrayList.size()]);
This code works also:
String[] myArray = myArrayList.toArray(new String[0]);
But it less effective: the string array is created twice: first time zero-length array is created, then the real-size array is created, filled and returned. So, if since you know the needed size (from list.size()) you should create array that is big enough to put all elements. In this case it is not re-allocated.
ArrayList<String> myArrayList = new ArrayList<String>();
...
String[] myArray = myArrayList.toArray(new String[0]);
Whether it's a "good idea" would really be dependent on your use case.
assuming v is a ArrayList:
String[] x = (String[]) v.toArray(new String[0]);
There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0])).
In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation.
You can follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).
This is the recommended usage for newer Java ( >Java 6)
String[] myArray = myArrayList.toArray(new String[0]);
In older Java versions using pre-sized array was recommended, as the
reflection call which is necessary to create an array of proper size
was quite slow. However since late updates of OpenJDK 6 this call was
intrinsified, making the performance of the empty array version the
same and sometimes even better, compared to the pre-sized version.
Also passing pre-sized array is dangerous for a concurrent or
synchronized collection as a data race is possible between the size
and toArray call which may result in extra nulls at the end of the
array, if the collection was concurrently shrunk during the operation.
This inspection allows to follow the uniform style: either using an
empty array (which is recommended in modern Java) or using a pre-sized
array (which might be faster in older Java versions or non-HotSpot
based JVMs).
Most answers work as accepted. But since Java 11, there's another way to use toArray() method using method reference operator or double colon operation (::).
Here's an example:
ArrayList<String> list = new ArrayList<>();
// ... add strings to list
// Since java 11
String[] strArray = list.toArray(String[]::new);
// before java 11, as specified in the official documentation.
strArray = list.toArray(new String[0]);
The Collection interface includes the toArray() method to convert a new collection into an array. There are two forms of this method. The no argument version will return the elements of the collection in an Object array: public Object[ ] toArray(). The returned array cannot cast to any other data type. This is the simplest version. The second version requires you to pass in the data type of the array you’d like to return: public Object [ ] toArray(Object type[ ]).
public static void main(String[] args) {
List<String> l=new ArrayList<String>();
l.add("A");
l.add("B");
l.add("C");
Object arr[]=l.toArray();
for(Object a:arr)
{
String str=(String)a;
System.out.println(str);
}
}
for reference, refer this link http://techno-terminal.blogspot.in/2015/11/how-to-obtain-array-from-arraylist.html
One approach would be to add the Second for Loop where the printing is being done inside the first for loop. Like this:
static String[] SENTENCE;
public static void main(String []args) throws Exception{
Scanner sentence = new Scanner(new File("assets/blah.txt"));
ArrayList<String> sentenceList = new ArrayList<String>();
while (sentence.hasNextLine())
{
sentenceList.add(sentence.nextLine());
}
sentence.close();
String[] sentenceArray = sentenceList.toArray(new String[sentenceList.size()]);
// System.out.println(sentenceArray.length);
for (int r=0;r<sentenceArray.length;r++)
{
SENTENCE = sentenceArray[r].split("(?<=[.!?])\\s*"); //split sentences and store in array
for (int i=0;i<SENTENCE.length;i++)
{
System.out.println("Sentence " + (i+1) + ": " + SENTENCE[i]);
}
}
}
ArrayList<String> a = new ArrayList<String>();
a.add( "test" );
#SuppressWarnings( "unused")
Object[] array = a.toArray();
It depends on what you want to achieve if you need to manipulate the array later it would cost more effort than keeping the string in the ArrayList. You have also random access with an ArrayList by list.get( index );
I usually use this method.
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
int[] arr = list.stream().mapToInt(i -> i).toArray();
System.out.println(Arrays.toString(arr)); // [1, 2, 3]
}

array of pair, ArrayList in java

how can I make array of ArrayList or Pair Class which I made myself at the code below.
ex1)
import java.util.*;
class Pair{
static int first;
static int second;
}
public class Main{
public static void main(String[] args){
Vector<Pair>[] v = new Vector<Pair>[100](); //this gives me an error
}
}
1.why the code above gives me an error?
2.my goal is to make an array of vector so that each index of vector holds one or more Pair classes. How can I make it?
another example) : array of ArrayList
import java.util.*;
public class Main{
public static void main(String[] args){
ArrayList<Integer> arr = ArrayList<Integer>(); //I know this line doesn't give error
ArrayList<Integer>[] arr = ArrayList<integer>[500]; // this gives me an error
}
}
3.why does the code above give me an error?
4.my goal is to make an array of ArrayList so that each index of Array has ArrayList/Queue/Vector/Deque whatever. How can I make it?
How about a full generic solution:
ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
The syntax you have used is not what Java uses. If you want to have an array of ArrayLists then do:
ArrayList[] arr = new ArrayList[100];
for(int i=0; i<arr.length; i++)
{
arr[i] = new ArrayList<Pair>(); // add ArrayLists to array
}
Here the type argument <Pair> specifies that the ArrayList should contain items of type Pair. But you can specify any type you wish to use. The same goes for ArrayList, you could replace ArrayList with Vector in the example.
It would be best to use an ArrayList instead of an array in the example. Its much easier to maintain without worrying about the changing length and indexes.
Hope this helps.
public static void main(String[] args){
Vector[] v = new Vector[5];
for(int i=0;i<5;++i){
v[i]= new Vector<Pair>();
}
}
I don't know java that well, but don't you want to do:
ArrayList<ArrayList<Pair>> v = new ArrayList<ArrayList<Pair>>();
Try to break down what containers you need in your question. Your goal is to make a ArrayList (ok, the outer ArrayList satisfies that purpose) that has one or more pair classes in that. "That has" means that "each item in the ArrayList is this type". What would we use to store one or more Pair classes? Another Vector/List of tyoe Pair. So each item in the outer ArrayList is another ArrayList of Pairs.
Note: I moved everything to ArrayList because I read that Vector is somewhat deprecated and they serve similar functions. You may want to check on this.
This example should help with with the next part of your question, but let me know if it doesn't,

Categories