I have two lists one is feature and has a placement number based on which i insert data in sorted list e.g if placement number is 5 data will be added in 5th position .i want to add data at 5th postion and to move data which was at 5th position to next index but in my case it just replace data at 5th position not move current data to next position
for (int i = 0; i < featuredList.size(); i++) {
int n = featuredList.get(i).getPlacementNumber().intValue();
if (n < sortedList.size()) {
sortedList.add(n, featuredList.get(i));
} else {
sortedList.add(featuredList.get(i));
}
}
You should use ArrayList, from add(int index, E element)
Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
Make your sortedList as ArrayList:
List<YourType> sortedList= new ArrayList<YourType>();
See the example http://ideone.com/L6hpsf
String s1 = "s1";
String s2 = "s2";
String s3 = "s3";
List<String> list = new ArrayList<String>();
list.add(s1);
list.add(s3);
list.add(1, s2);
System.out.println(list);
Output: [s1, s2, s3]
Try to use LinkedList to insertion or deletion between list for better performance then ArrayList :
private LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("1");
linkedList.add("2");
linkedList.add("3");
linkedList.add("4");
linkedList.add("5");
// insertion at 3 position
linkedList.add(2,"6");
Another example which may give you some clue and even easy to run :)
import java.util.ArrayList;
public class Alisttest {
public static void main(String[] args) {
ArrayList a = new ArrayList();
a.add("1");
a.add("2");
a.add("3");
a.add("4");
System.out.println("a=> "+a.get(2));
a.add(2, "Pankaj");
System.out.println("a=> "+a.get(2));
System.out.println();
System.out.println("a=> "+a);
}
}
Related
I have two fields in my custom class List:
LinkedList<String> breadList;
Iterator<String> iterator.
And I've defined two methods:
showBreadList() - for displaying the contents of the list;
addInOrder() - for inserting a new element into the list (the list should be updated in such a way so that elements are maintained in sorted order).
My code:
public class List {
class LinkedListExample {
private LinkedList<String> breadList = new LinkedList<>(); // <-- Edit from the answer: public to private
Iterator<String> iterator;
public void showBreadList() {
iterator = breadList.iterator();
System.out.println("Values in breadList: ");
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
}
public void addInOrder(String bread) {
ListIterator<String> stringListIterator = breadList.listIterator();
while(stringListIterator.hasNext()) {
if(stringListIterator.next().compareTo(bread) == 0) {
} else if(stringListIterator.next().compareTo(bread) > 0) {
stringListIterator.previous();
stringListIterator.add(bread);
} else if(stringListIterator.next().compareTo(bread) < 0) {
}
}
stringListIterator.add(bread); // <-- Edit: added
}
}
public static void main(String[] args) {
List list = new List();
List.LinkedListExample lle = list.new LinkedListExample();
lle.addInOrder("Ciabatta");
lle.addInOrder("Wheat Bread");
lle.addInOrder("White Bread");
lle.addInOrder("Sourdough");
lle.addInOrder("Flatbread");
lle.showBreadList();
}
}
The list gets populated in the main() method via addInOrder().
Expected output:
Values in breadList:
Ciabatta
Flatbread
Sourdough
Wheat Bread
White Bread
Actual output:
Value in breadList:
I.e. I'm getting nothing. Can anybody give a hint on what I'm doing wrong?
Seems like the goal of your assignment is to learn how to deal with a ListIterator.
The core thing to understand about the Iterators that their cursor always occupies a position in between the elements of the list (and it might also be positioned before the first element and right after the last element). And that's the position where a new element gets inserted when you invoke ListIterator.add().
Here's a quote from the official tutorial Provided by Oracle:
Intuitively speaking, the cursor is always between two elements — the
one that would be returned by a call to previous and the one that
would be returned by a call to next. The n+1 valid index values
correspond to the n+1 gaps between elements, from the gap before the
first element to the gap after the last one. The following figure
shows the five possible cursor positions in a list containing four
elements.
In the method addInOrder() you've messed around with conditions. If fact, only one condition that would check if the next is lexicographically greater than the given string would be enough. If the next is greater we continue iteration, if not we need to move the iterator the previous position by calling previous() and then break from the loop.
Method add() will be invoked on the iterator after the loop, when iterator is the right position to insert a new element.
That's how you can fix your method:
public void addInOrder(String bread) {
ListIterator<String> iterator = breadList.listIterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (next.compareTo(bread) > 0) { // if the next element is lexicographically greater than `bread`, `bread` has to be inserted before it
iterator.previous(); // moving to the position where the new `bread` should be inserted
break; // breaking out from the loop
}
}
iterator.add(bread); // inserting the new kind of bread
}
Example with the sample data from the question:
LinkedListExample lle = new LinkedListExample();
lle.addInOrder("Ciabatta");
lle.addInOrder("Wheat Bread");
lle.addInOrder("White Bread");
lle.addInOrder("Sourdough");
lle.addInOrder("Flatbread");
lle.showBreadList();
Output:
Ciabatta
Flatbread
Sourdough
Wheat Bread
White Bread
I am looking at the code for Permutations problem on leetcode. For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
And I found there is one sentence
ArrayList<Integer> temp = new ArrayList<Integer>(l);
I have no idea why here needs to assign the "l" to "temp". And I tried current.add(l) direclty but gave me the wrong answer. Can you help me with this?
public class Solution {
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
//start from an empty list
result.add(new ArrayList<Integer>());
for (int i = 0; i < num.length; i++) {
//list of list in current iteration of the array num
ArrayList<ArrayList<Integer>> current = new ArrayList<ArrayList<Integer>>();
for (ArrayList<Integer> l : result) {
// # of locations to insert is largest index + 1
for (int j = 0; j < l.size()+1; j++) {
// + add num[i] to different locations
l.add(j, num[i]);
ArrayList<Integer> temp = new ArrayList<Integer>(l);
current.add(temp);
//System.out.println(temp);
// - remove num[i] add
l.remove(j);
}
}
result = new ArrayList<ArrayList<Integer>>(current);
}
return result;
}
}
I have no idea why here needs to assign the "l" to "temp"
He's not - that would just be:
ArrayList<Integer> temp = l;
Instead, the code creates a copy of the content of the list l refers to, in a new ArrayList. That means that future changes to the list that l refers to (such as the call to l.remove(j) immediately afterwards) don't affect the new list.
As a simple stand-alone example of that, consider:
List<String> original = new ArrayList<>();
original.add("foo");
List<String> copy = new ArrayList<>(original);
System.out.println(copy.size()); // 1
original.add("bar");
System.out.println(copy.size()); // Still 1
Admittedly the code is written in a very odd manner - until the final statement, result only ever has a single element, so iterating over it is pretty pointless - but I believe that explains the single statement you were asking about.
If you did
current.add(l);
you would be adding the same reference to the ArrayList l to current. So, if you made some changes in one of those lists, both would be modified. In order to avoid that issue, in the line
ArrayList<Integer> temp = new ArrayList<Integer>(l);
you are creating a different ArrayList but with the same content. So, they will be different objects (different references).
Recently while using arrayList I found a weird issue. I want to keep 2 elements in the arraylist and would like to keep object1 in element 0 and object2 in element1.
I am deciding this in a loop.
When it happens to add the first element its throwing indexOutofBounds. As per java doc as the index is greater than size its doing this.
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
list.add(1,"SECONDITEM"); // throwing due to size is not set
list.add(0,"FIRSTITEM");
int postn=0;
for(String item:list){
System.out.println("Position "+postn+" :"+item);
postn++;
}
}
Then I tried to setup other items as placeholder in 0,1 element and tried to do same
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
list.add(0,"x");
list.add(1,"y");
list.add(1,"SECONDITEM");
list.add(0,"FIRSTITEM");
int postn=0;
for(String item:list){
System.out.println("Position "+postn+" :"+item);
postn++;
}
}
Output:
Position 0 :FIRSTITEM
Position 1 :x
Position 2 :SECONDITEM
Position 3 :y
How to get over this issue. One way I found is to remove the element in the index and add the element. Is there a better option.
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
list.add(0,"x");
list.add(1,"y");
list.remove(1);
list.add(1,"SECONDITEM");
list.remove(0);
list.add(0,"FIRSTITEM");
int postn=0;
for(String item:list){
System.out.println("Position "+postn+" :"+item);
postn++;
}
}
Position 0 :FIRSTITEM
Position 1 :SECONDITEM
.add() method insert the element at the given position and shift the other element accordingly
to overwrite the value at particular index you have to use the .set(position, value)
try the set method ..
list.add(0,"x");
list.add(1,"y");
list.set(1,"SECONDITEM");
list.set(0,"FIRSTITEM");
now it will return the only two values.
When you call in this order:
ArrayList<String> list = new ArrayList<String>();
list.add(1,"SECONDITEM"); // throwing due to size is not set
You are trying to add to position "1", but nothing has been added to the list yet. I believe that is why you get the error. Instead you probably want to use just:
ArrayList<String> list = new ArrayList<String>();
list.add("FIRSTITEM");
Since it's an empty list. You can also use the index, but you'll have to increment each time. Makes sense?
The issue is ... you're trying to use a List in a way it wasn't intended to be used. As you've found out, you can't set or add to an index that is outside the range of the current size.
If you know in advance the size you need and it's a fixed size, using a String[] is the better choice.
If you really want/need a dynamic structure that allows random access sets regardless of the current size, write your own method to fill the list when needed:
public static <T> void fillAndSet(int index, T object, List<T> list)
{
if (index > (list.size() - 1))
{
for (int i = list.size(); i < index; i++)
{
list.add(null);
}
list.add(object);
}
else
{
list.set(index, object);
}
}
I'm fairly new to Java and I've been trying to solve the following problem unsuccessfully.
Write a Java method that will remove duplicates from a given list.
Assuming:
Method accepts type List
Return type is void
Duplicates are determined using equals()
Main:
Creates an instant of List and loads it with duplicate String values
Invoke removeDuplicates(), pass in this list
Outputs modified list to the console.
I can solve the problem by passing in my list to a new HashSet and copy it back.
But the problem is:
Question is asking me to solve it using equals()...
If the return type is void, how can i output it in the main ?
import java.util.*;
public class Question1 {
public static void main(String[] args) {
String[] words = {"good","better", "best", "best", "first" , "last", "last", "last", "good"};
List<String> list = new ArrayList<String>();
for (String s : words) {
list.add(s);
}
removeDuplicates(list);
}
static void removeDuplicates(List<String> array){
HashSet<String> hs = new HashSet<>();
hs.addAll(array);
array.clear();
array.addAll(hs);
for (String x : array){
System.out.println(x);
}
}
}
EDIT: well, this one works, but as you can see i'm not using equals() and i'm printing out from my static method, not from main.
Also, is there any way I can populate the List faster than using String[] ?
java.util.HashSet uses Object.equals(Object) in its implementation of Set.add(Object) to determine that the element being inserted is unique (as defined by not being equal to another element). HashSet also has the advantage of allowing you to do the de-duping process in O(n) time vs a more naive approach of comparing every element to every other element in O(n^2) time.
The code in main will see the modified list, because the List object is mutable. When a method changes the state of a passed in argument the calling code will see those changes.
removeDuplicates creates a set, then iterates over the input list. If it encounters an element in the input list, that is also in the set, removeDuplicates removes the element from the input list, otherwise it adds the element to the set.
Java is a call-by-reference language (sort of). This means, the method removeDuplicates can modify the List<String> array that it receives and the caller will see that modified list after the call to removeDuplicates returned.
Here's how you would do the same thing without using a Set and just using equals() (also to somewhat answer your "EDIT" question about initializing a List) :
public static void main(String[] args) {
List<String> list = new ArrayList<String>(Arrays.asList(new String[] {
"good", "better", "best", "best", "first", "last", "last", "last",
"good"}));
removeDuplicates(list);
for (String x : list) {
System.out.println(x);
}
}
static void removeDuplicates(List<String> array) {
for (int i = 0; i < array.size(); i++) {
String next = array.get(i);
// check if this has already appeared before
for (int j = 0; j < i; j++) {
// if it has, stop the search and remove it
if (next.equals(array.get(j))) {
array.remove(i);
// decrement i since we just removed the i'th element
i--;
// stop the search
break;
}
}
}
}
That said, using HashSet is a better idea since as has already been pointed out it is more efficient.
If you want the efficiency of HashSet but still preserve the order of the List you could do something like this :
static void removeDuplicates(List<String> array) {
Set<String> set = new HashSet<String>();
for (int i = 0; i < array.size(); i++) {
String next = array.get(i);
// check if this has already appeared before
if (!set.add(next)) {
// if it has then remove it
array.remove(i);
// decrement i since we just removed the i'th element
i--;
}
}
}
The probably easiest way would be to use a Set in the first place, which by definition does not allow duplicates.
For your actual problem, you can do several approaches:
The easy but slow approach: compare each element A with each other element N in the list. If A.equals(N) remove N. Hint: you only need to compare A to each further element, as you have already checked each element before A.
The faster approach: sort the list using the natural comperator. Now you no longer need to compare each element A vs N, but only A vs the next few elements. To be exact: until you find the first element that is not equal to A. In this case you can assume that there is no further duplicate of A (thanks to the sorting) and continue with this next element as A.
The Map approach (fast but takes more memory): for each element put into the list, put the same element into a Map with any Object as value. Now you can just look-up whether or not that element is already in the map, and if it is, it is a duplicate.
The best way would be the 2nd approach as the sorting is very fast, you only need to get each element once, and there is no 2nd list necessary.
Edit: The 2nd approach in code:
static void removeDuplicates(List<String> array) {
if (array.size() <= 1) {
return;
}
Collections.sort(array);
final Iterator<String> it = array.iterator();
String a = it.next(), n;
while (it.hasNext()) {
n = it.next();
if (((a == null) && (n != null))
|| ((a != null) && (a.equals(n) == false))) {
a = n;
} else {
it.remove();
}
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("good");
list.add("better");
list.add("best");
list.add("best");
list.add("first");
list.add("last");
list.add("last");
list.add("last");
list.add("good");
removeDuplicates(list);
System.out.println(list.toString());
}
public static void removeDuplicates(List<String> list) {
if (list != null) {
for (int i = 0; i < list.size(); i++) {
ListIterator<String> listIterator = list.listIterator();
while (listIterator.hasNext()) {
int nextIndex = listIterator.nextIndex();
String nextElement = listIterator.next();
if (list.get(i).equals(nextElement) && i != nextIndex)
listIterator.remove();
}
}
}
}
}
I'm new to java (& to OOP too) and I'm trying to understand about the class ArrayList
but I don't understand how to use the get(). I tried searching in net, but couldn't find anything helpful.
Here is the official documentation of ArrayList.get().
Anyway it is very simple, for example
ArrayList list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
String str = (String) list.get(0); // here you get "1" in str
To put it nice and simply, get(int index) returns the element at the specified index.
So say we had an ArrayList of Strings:
List<String> names = new ArrayList<String>();
names.add("Arthur Dent");
names.add("Marvin");
names.add("Trillian");
names.add("Ford Prefect");
Which can be visualised as:
Where 0, 1, 2, and 3 denote the indexes of the ArrayList.
Say we wanted to retrieve one of the names we would do the following:
String name = names.get(1);
Which returns the name at the index of 1.
So if we were to print out the name System.out.println(name); the output would be Marvin - Although he might not be too happy with us disturbing him.
You use List#get(int index) to get an object with the index index in the list. You use it like that:
List<ExampleClass> list = new ArrayList<ExampleClass>();
list.add(new ExampleClass());
list.add(new ExampleClass());
list.add(new ExampleClass());
ExampleClass exampleObj = list.get(2); // will get the 3rd element in the list (index 2);
ArrayList get(int index) method is used for fetching an element from the list. We need to specify the index while calling get method and it returns the value present at the specified index.
public Element get(int index)
Example :
In below example we are getting few elements of an arraylist by using get method.
package beginnersbook.com;
import java.util.ArrayList;
public class GetMethodExample {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("pen");
al.add("pencil");
al.add("ink");
al.add("notebook");
al.add("book");
al.add("books");
al.add("paper");
al.add("white board");
System.out.println("First element of the ArrayList: "+al.get(0));
System.out.println("Third element of the ArrayList: "+al.get(2));
System.out.println("Sixth element of the ArrayList: "+al.get(5));
System.out.println("Fourth element of the ArrayList: "+al.get(3));
}
}
Output:
First element of the ArrayList: pen
Third element of the ArrayList: ink
Sixth element of the ArrayList: books
Fourth element of the ArrayList: notebook
Would this help?
final List<String> l = new ArrayList<String>();
for (int i = 0; i < 10; i++) l.add("Number " + i);
for (int i = 0; i < 10; i++) System.out.println(l.get(i));
The get() method returns an element. For example:
ArrayList<String> name = new ArrayList<String>();
name.add("katy");
name.add("chloe");
System.out.println("The first name in the list is " + name.get(0));
System.out.println("The second name in the list is " + name.get(1));
The output:
The first name in the list is katy
The second name in the list is chloe