Manipulating section of arraylist in Java - java

I have a matrix of W of large row and column dimension. Each of the row represents feature values(filled with double value).And the matrix is constructed as:
Hashmap<Integer,Arraylist<Double>> W = new Hashmap<Integer,Arraylist<Double>>();
While making computation, I need to take certain portion of each of the rows and update them in matrix. I looked for subList method in Arraylist. But the problem is it returns only list but I am in need of arraylist. Because many of the methods that I have already implemented take <Arraylist> as argument. So what can be the solution for this case?
Example
w1 = [1,3 ,4,6,9,1,34,5,21,5,2,5,1]
w11 = [1,3,4]
w11 = w11 +1 = [2,4,5]
This changes w1 to = [2,4 ,5,6,9,1,34,5,21,5,2,5,1]

I looked for subList method in Arraylist.But the problem is it returns only list but i am in need of arraylist
That is not a problem at all. In fact, you should change your code to use List wherever possible.
A List is an interface which concrete types such as the ArrayList implement. The below is perfectly valid:
List<String> list = new ArrayList<String>();
list.add("hello");
list.add("world");
I recommend changing your W to this:
Hashmap<Integer, List<Double>> W = new Hashmap<Integer, List<Double>>();

You could subclass ArrayList to provide a view of a slice of another ArrayList. Like this:
class ArrayListSlice<E> extends ArrayList<E> {
private ArrayList<E> backing_list;
private int start_idx;
private int len;
ArrayListSlice(ArrayList<E> backing_list, int start_idx, int len) {
this.backing_list = backing_list;
this.start_idx = start_idx;
this.len = len;
}
public E get(int index) {
if (index < 0 || idx >= len) throw new IndexOutOfBoundsException();
return backing_list.get(start_idx + index);
}
... set, others? ...
}
Then you can do w11 = new ArrayListSlice<Double>(w1, 0, 3). Any operations on w11 will appear in w1, assuming you implement set correctly.
You will probably need to implement most the methods of ArrayList to make this work. Some may work if they just rely on others, but that's hard to tell from the spec.

Related

How to add members to the back or front of an array list

I am trying to use array lists, and I have a row of coordinates. I would like to shift all the coordinates in this row to the front or to the back. I'm not sure if I am on the correct lines here with the code.
List<Coordinate> coordinates = new ArrayList<>();
void addCoordinateToList(Coordinate singleCoordinate) {
coordinates.add(singleCoordinate)
}
void addCoordinateToBackList(ArrayList<> coordinateList) {
for(int i = 0; i < coordinates.size(); i++) {
coordinateList.add(i, coordinateList(i));
}
}
void addCoordinateToFrontList(ArrayList<> coordinateList) {
for(int i = coordinates.size(); i > 0; i--) {
coordinateList.add(i, coordinatesList(i));
}
}
This is not final code, its just writing thoughts out at the moment.
Well, you don't need to use a for loop here.
You could instead utilize the addAll method to achieve what you want:
void addCoordinatesToBack(List<Coordinate> coordinateList) {
coordinates.addAll(coordinateList);
}
void addCoordinatesToFront(List<Coordinate> coordinateList) {
coordinates.addAll(0, coordinateList);
}
addAll has two forms:
addAll(Collection c) adds all elements of the specified Collection at the end of the list;
addAll(int position, Collection c) adds all elements of the specified Collection at the given position. Use position 0 to add them at the beginning of the list.
Also note that I have used List instead of ArrayList with your parameters, as this makes it more flexible.
Note that this is not quite the same as reversing lists.
This functionality is built into the List interface. You can use the following functions for that:
List<String> myList = new ArrayList<>();
//adds to the end of the list
myList.add("reading");
myList.addAll(List.of("the","documentation","first!"));
//adds to the front of the list
myList.add(0,"with");
myList.addAll(0,List.of("It","begins");
Your code
void addCoordinateToBackList(ArrayList<> coordinateList) {
for(int i = 0; i < coordinates.size(); i++) {
coordinateList.add(i, coordinateList.get(i));
}
}
will endlessly add the first element of the original list to beginning of itself. Note that I added the call to List.get(int).
Your last method will throw an ArrayIndexOutOfBounds exception as index i=coordinates.size() is out of bounds. You probably need to change
void addCoordinateToFrontList(ArrayList<> coordinateList) {
for(int i = coordinates.size() - 1; i >= 0; i--) {
coordinateList.add(i, coordinatesList.get(i));
}
}
But this will again add endlessly the last element of the list to itself.
Probably what you want to achieve is:
List<Object> coordinateList = new ArrayList<>();
...
java.util.Collections.reverse(coordinateList);
This will reverse the order of the elements in the list. Note that it will work on the given list and not return anything. This will work only on modifiable lists.
EDIT:
You probably mean to "rotate" the elements, right? There is also the method Collections.rotate(List input, int distance). The documentation:
Rotates the elements in the specified list by the specified distance. After calling this method, the element at index i will be the element previously at index (i - distance) mod list.size(), for all values of i between 0 and list.size()-1, inclusive. (This method has no effect on the size of the list.)
For example, suppose list comprises [t, a, n, k, s]. After invoking Collections.rotate(list, 1) (or Collections.rotate(list, -4)), list will comprise [s, t, a, n, k].
This works in both directions.

Using List, how would I change this code as using List

So I have this code at the bottom, and I have to Instantiate myArray to a new array. Copy all data from int[] data to myArray. Set numMoves equal to 0. data Array holding the values input from the user. So this code I have here is done by just using int and just = signs and new, But now I need to change this Using "List" and I do not know what list is and how to use it. So what I need help on is What is List on java and how would I do this using List. Thanks, and i prefer telling me how it works thank you!
public class Deletions
{
private int[] myArray;
private int numMoves;
public Deletions(int[] data)
{
myArray = new int [data.length] ;
for(int n = 0; n < data.length; n++)
{
myArray[n] = data[n];
}
numMoves = 0;
}
At first, the original array copy method can be written like this.
int[] myArray = new int[data.length];
System.arraycopy(data, 0, myArray, 0, data.length);
and then, the solution will be
public List<Integer> copyToList(int[] data){
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < data.length; i++) {
list.add(data[i]);
}
return list;
}
or
public List<Integer> copyFromToList(List<Integer> data){
return new ArrayList<Integer>(data);
}
List is an ordered collection also known as Sequence. With ordered, it means that one can retrieve elements in the same Sequence as one has inserted the element into the List. Another important thing, List is interface not a concrete implementation. For concrete implementation, look at LinkedList/ArrayList etc.
To achieve the same result, I would write something like this:-
new ArrayList<>(Arrays.asList(data));
A list is any class whose instances can contain an ordered sequence of objects.
In Java, you most likely want to use ArrayList<E>, which is the generic list. Generic means that you can put whatever type of object in the list, as long as you specify that type (or one of its base types) in place of the E. An ArrayList<E> has methods such as add, get, and set.
For example:
ArrayList<Integer> myList = new ArrayList<Integer>();
myList.add(1337);
myList.add(42);
Look at the ArrayList<E> documentation for more information on what methods are available to you.
public class Deletions
{
private ArrayList<Integer> myArray;
private int numMoves;
public Deletions(int[] data)
{
myArray = new ArrayList<Integer>();
for(int n = 0; n < data.length; n++)
{
myArray.add(data[n]);
}
numMoves = 0;
}
}
http://docs.oracle.com/javase/tutorial/collections/implementations/list.html

Cartesian Products with sets in java

I am trying to create a cartesian product method in java that accepts sets as arguments and returns a set pair. The code I have coverts the argumented sets to arrays and then does the cartesian product but i can't add it back to the set pair that i want to return. Is there an easier way to do this? Thanks in advance.
public static <S, T> Set<Pair<S, T>> cartesianProduct(Set<S> a, Set<T> b) {
Set<Pair<S, T>> product = new HashSet<Pair<S, T>>();
String[] arrayA = new String[100];
String[] arrayB= new String[100];
a.toArray(arrayA);
b.toArray(arrayB);
for(int i = 0; i < a.size(); i++){
for(int j = 0; j < b.size(); j++){
product.add(arrayA[i],arrayB[j]);
}
}
return product;
}
this looks simpler,
public static <S, T> Set<Pair<S, T>> cartesianProduct(Set<S> a, Set<T> b) {
Set<Pair<S, T>> product = new HashSet<Pair<S, T>>();
for(S s : a) {
for(T t : b) {
product.add(new ImmutablePair<S, T>(s,t));
}
}
return product;
}
Assuming you're using Pair from Apache Commons, then I think you want the add to be
product.add(Pair.of(arrayA[i],arrayB[j]));
There's no add method for sets that takes two arguments. You have to create the Pair to add to the set. If that doesn't compile, try
product.add(Pair<S,T>.of(arrayA[i],arrayB[j]));
Also, I'm assuming you meant S and T for your arrays, instead of String. There's no reason to preallocate a certain number of elements. Furthermore, the way you've written it, if there are more than 100 elements in either set, toArray will return an all new array with the desired size, but you're not using the function result so that array will be lost. I'd prefer:
S[] arrayA = a.toArray(new S[0]);
T[] arrayB = b.toArray(new T[0]);
The zero-length arrays are just "dummies" whose purpose is to get toArray to return arrays with the correct element type, instead of Object[].
EDIT: Using an enhanced for loop is a lot better than using arrays. See Camilo's answer.

Manilpulate multiple ArrayLists with loops

I have a large number of ArrayLists, and I want to be able to manipulate them using for loops. If they are named p1, p2, p3 ... pn, how can I perform a task such as .get(0) for all of them using a loop instead of
p1.get(0);
p2.get(0);
p3.get(0);
pn.get(0);
public class ListsExample {
public static void main(String[] args) {
List<Integer> p1 = Arrays.asList(1,2,3,4,5);
List<Integer> p2 = Arrays.asList(1,2,3,4,5);
List<Integer> p3 = Arrays.asList(1,2,3,4,5);
List<List<Integer>> lists = new ArrayList<List<Integer>>();
lists.add(p1);
lists.add(p2);
lists.add(p3);
for(List<Integer> list : lists){
System.out.println(list.get(0));
}
}
}
Place your ArrayLists in an ArrayList. Access them in a for loop, then call get(0) on your retrieved ArrayList.
You could put them all into a list and loop over them
List<ArrayList> lists = new LinkedList<ArrayList>();
lists.add(p1);
lists.add(p2);
for ( ArrayList list : lists ) {
list.get(0);
}
Your question is unclear. If you mean how to access the four separate arrays in a loop...
for (int i = 0; i < ...; ++ i) {
p1.get(i);
p2.get(i);
p3.get(i);
pn.get(i);
}
If you mean you have four equal-sized arrays and you want to group the data together more conveniently, then ditch the four areas, make a class with the relevant fields to store your data in instead, and use a single array of that:
class Item {
Whatever v1;
Whatever v2;
Whatever v3;
Whatever vn;
}
ArrayList<Item> items = ...;
items.get(0);
If you mean you have a variable number of those arrays and you want to select which one you access dynamically, you can use an ArrayList of the original ArrayLists:
List<ArrayList<Whatever>> p = getListOfAllMyArrayLists();
p.get(n).get(0);
If you want to keep all your separate arrays for some reason (maybe you can't refactor) and just want a convenient way to access all the data at once, you can write a method to do that and pack the results into their own array, e.g.:
public List<Whatever> getAll (int x) {
List<Whatever> values = new ArrayList<Whatever>();
values.add(p1.get(x));
values.add(p2.get(x));
values.add(p3.get(x));
values.add(pn.get(x));
return values;
}
You could also implement getAll() to take a variable number of source arrays if you use an ellipses parameter.
I hope one of these is helpful.

How can I dynamically add items to a Java array?

In PHP, you can dynamically add elements to arrays by the following:
$x = new Array();
$x[] = 1;
$x[] = 2;
After this, $x would be an array like this: {1,2}.
Is there a way to do something similar in Java?
Look at java.util.LinkedList or java.util.ArrayList
List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
Arrays in Java have a fixed size, so you can't "add something at the end" as you could do in PHP.
A bit similar to the PHP behaviour is this:
int[] addElement(int[] org, int added) {
int[] result = Arrays.copyOf(org, org.length +1);
result[org.length] = added;
return result;
}
Then you can write:
x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);
System.out.println(Arrays.toString(x));
But this scheme is horribly inefficient for larger arrays, as it makes a copy of the whole array each time. (And it is in fact not completely equivalent to PHP, since your old arrays stays the same).
The PHP arrays are in fact quite the same as a Java HashMap with an added "max key", so it would know which key to use next, and a strange iteration order (and a strange equivalence relation between Integer keys and some Strings). But for simple indexed collections, better use a List in Java, like the other answerers proposed.
If you want to avoid using List because of the overhead of wrapping every int in an Integer, consider using reimplementations of collections for primitive types, which use arrays internally, but will not do a copy on every change, only when the internal array is full (just like ArrayList). (One quickly googled example is this IntList class.)
Guava contains methods creating such wrappers in Ints.asList, Longs.asList, etc.
Apache Commons has an ArrayUtils implementation to add an element at the end of the new array:
/** Copies the given array and adds the given element at the end of the new array. */
public static <T> T[] add(T[] array, T element)
I have seen this question very often in the web and in my opinion, many people with high reputation did not answer these questions properly. So I would like to express my own answer here.
First we should consider there is a difference between array and arraylist.
The question asks for adding an element to an array, and not ArrayList
The answer is quite simple. It can be done in 3 steps.
Convert array to an arraylist
Add element to the arrayList
Convert back the new arrayList to the array
Here is the simple picture of it
And finally here is the code:
Step 1:
public List<String> convertArrayToList(String[] array){
List<String> stringList = new ArrayList<String>(Arrays.asList(array));
return stringList;
}
Step 2:
public List<String> addToList(String element,List<String> list){
list.add(element);
return list;
}
Step 3:
public String[] convertListToArray(List<String> list){
String[] ins = (String[])list.toArray(new String[list.size()]);
return ins;
}
Step 4
public String[] addNewItemToArray(String element,String [] array){
List<String> list = convertArrayToList(array);
list= addToList(element,list);
return convertListToArray(list);
}
You can use an ArrayList and then use the toArray() method. But depending on what you are doing, you might not even need an array at all. Look into seeing if Lists are more what you want.
See: Java List Tutorial
You probably want to use an ArrayList for this -- for a dynamically sized array like structure.
You can dynamically add elements to an array using Collection Frameworks in JAVA. collection Framework doesn't work on primitive data types.
This Collection framework will be available in "java.util.*" package
For example if you use ArrayList,
Create an object to it and then add number of elements (any type like String, Integer ...etc)
ArrayList a = new ArrayList();
a.add("suman");
a.add(new Integer(3));
a.add("gurram");
Now you were added 3 elements to an array.
if you want to remove any of added elements
a.remove("suman");
again if you want to add any element
a.add("Gurram");
So the array size is incresing / decreasing dynamically..
Use an ArrayList or juggle to arrays to auto increment the array size.
keep a count of where you are in the primitive array
class recordStuff extends Thread
{
double[] aListOfDoubles;
int i = 0;
void run()
{
double newData;
newData = getNewData(); // gets data from somewhere
aListofDoubles[i] = newData; // adds it to the primitive array of doubles
i++ // increments the counter for the next pass
System.out.println("mode: " + doStuff());
}
void doStuff()
{
// Calculate the mode of the double[] array
for (int i = 0; i < aListOfDoubles.length; i++)
{
int count = 0;
for (int j = 0; j < aListOfDoubles.length; j++)
{
if (a[j] == a[i]) count++;
}
if (count > maxCount)
{
maxCount = count;
maxValue = aListOfDoubles[i];
}
}
return maxValue;
}
}
This is a simple way to add to an array in java. I used a second array to store my original array, and then added one more element to it. After that I passed that array back to the original one.
int [] test = {12,22,33};
int [] test2= new int[test.length+1];
int m=5;int mz=0;
for ( int test3: test)
{
test2[mz]=test3; mz++;
}
test2[mz++]=m;
test=test2;
for ( int test3: test)
{
System.out.println(test3);
}
In Java size of array is fixed , but you can add elements dynamically to a fixed sized array using its index and for loop. Please find example below.
package simplejava;
import java.util.Arrays;
/**
*
* #author sashant
*/
public class SimpleJava {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
String[] transactions;
transactions = new String[10];
for(int i = 0; i < transactions.length; i++){
transactions[i] = "transaction - "+Integer.toString(i);
}
System.out.println(Arrays.toString(transactions));
}catch(Exception exc){
System.out.println(exc.getMessage());
System.out.println(Arrays.toString(exc.getStackTrace()));
}
}
}

Categories

Resources