I'm having issues understanding ArrayList in Java. I tried to declare a Character ArrayList and add a char at 0, but it returned error at list.add(0, "B") line.
public class ArrListTest {
public static void main(String[] args) {
ArrayList<Character> list;
list.add(0, "B");
}
}
Also I'm having issues reversing a string. Is there a way to reverse a string without using a loop?
"B" is instance of String, characters need to be surrounded with ' like 'B'.
use
list.add(0,'B');
If you want to add B after last element of list skip 0
list.add('B');
Also don't forget to actually initialize your list
List<Character> list = new ArrayList<>();
// ^^^^^^^^^^^^^^^^^^^
To know why I used List<Character> list as reference type instead of ArrayList<Character> list read:
What does it mean to “program to an interface”?
You're mixing up List.set with List.add. Use a character literal instead of a String and use
list.add('B');
after initializing the List
List<Character> list = new ArrayList<>();
public class stackQuestions {
public static void main(String args[]) {
ArrayList list = new ArrayList();
list.add("b");
list.add(0, "a");// it will add to index 0
list.add(0, "c");// it will replaces to index 0
System.out.println(list);
}
}
public static void main(String args[]) {
ArrayList list= new ArrayList();
list.add("B");
}
try this
Related
I have an array list of String element I want to duplicate last element of that list and that duplicate element set in the 0th position of same list. how to duplicate array list.
below is my input list:
List ["Apple","Tomato","Patato","Brinjal","Cabbage"]
I want below type of list as output:
List ["Cabbage","Apple","Tomato","Patato","Brinjal","Cabbage"]
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Apple");
cars.add("Tomato");
cars.add("Patato");
cars.add("Cabbage");
System.out.println(cars);
}
}
You can do something like this:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Apple");
cars.add("Tomato");
cars.add("Patato");
cars.add("Cabbage");
// Geting the last element of the list
String lastElement = cars.get(cars.size() - 1);
// Adding the last element to the starting of the list
cars.add(0, lastElement);
System.out.println(cars); // This should out put your expected result.
}
}
Since you specify needing a copy of the list, you might add the last element to an empty ArrayList<String> then use addAll to add the original list elements.
ArrayList<String> copiedArraylist = new ArrayList<String>();
copiedArraylist.add(cars.get(cars.size()-1);
copiedArraylist.addAll(1, cars);
This is the class with the buildList method which builds the in
class Recursive
{
public static ArrayList<Integer> reversedList = new ArrayList<Integer>();
public static ArrayList<Integer> buildList(int n)//builds the arrayList based on integer. If the int is 5 then the contents are 1,2,3,4,5.
{
// write this in terms of a recursive call using a smaller n
ArrayList<Integer> tempList = null;
if (n <= 0) // The smallest list we can make
{
return new ArrayList<Integer>();
}
else // All other size lists are created here
{
tempList= buildList(n-1);
tempList.add(n);
}
return tempList;
}
This is the problem method. Idk why it returns [], I think there is a passing error.
public static ArrayList<Integer> reverse(ArrayList<Integer> lst)//the problem method
{
if(lst.size()<=0) {
}
else {
reversedList.add(lst.remove(lst.size()-1));
reverse(lst);
}
return reversedList;
}
public static void main(String[] args)
{
ArrayList<Integer> lst = Recursive.buildList(5);
System.out.println(lst);
reverse(lst);
System.out.println(lst);
}
}
The reverse method removes the last item of lst and adds it to the empty reversedList. After the first iteration the contents should be [5]. Second [5,4]...all the way to [5,4,3,2,1]. But somehow it ends up being [].
So the reverse method is supposed to print out [5,4,3,2,1] but rather prints []. I think it has something to do with passing the reversedList between the if and else statement but I'm not sure.
You are printing the original list lst only which is now empty as program has removed all the elements.
You must reassign the lst to new object reference returned from function like lst = reverse(lst);
OR you can use System.out.println(reversedList)
public static void main(String[] args)
{
ArrayList<Integer> lst = Recursive.buildList(5);
System.out.println(lst);
lst = reverse(lst); ////update lst reference
System.out.println(lst);
System.out.println(reversedList); //// OR print reversedList directly
}
Hope you find it helpful.
I want to know the shortcut for doing this :
class{ ArrayList a1=new ArrayList();
ArrayList a2=new ArrayList();
ArrayList a3=new ArrayList();
.....& so on
}
So instead of writing each reference, how can I write an array of references 'with ArrayList' ?
you can use `List<ArrayList> list = new ArrayList<ArrayList>();`. In this you can add any number of `ArrayList` Objects to `list` reference.
Find the below :
List<ArrayList> list = new ArrayList<ArrayList>();
list.add(new ArrayList());
list.add(new ArrayList());
list.add(new ArrayList());
list.add(new ArrayList());
// ....
list hold ArrayList references in inserted order. You can access the ArrayList using index which zero based.
// to access the ArrayList reference.
ArrayList a1 = list.get(0);
Use an array of ArrayList. And loop.
ArrayList a1, a2, ... , a100;
ArrayList[] arrayLists = new ArrayList[100];
for (ArrayList arrayList : arrayLists) {
arrayList = new ArrayList();
}
But creating different references array is not a good design.
For example you can create array list array like below:
ArrayList[] a = new ArrayList[4];
Before implementing this you clear with your requirement , why you need to create these many references.
And also while creating ArrayList it's better to use reference creation like below:
List<String> a = new ArrayList<String>();
Always use generics while working on JAVA collections.
For your requirement to store word and it's permutations, I would suggest below process:
Step1: Create WordPermutations class
public Class WordPermutations{
public string word;
public ArrayList<String> permutations = new ArrayList<String>();
public void setWord(String word){
this.word = word;
}
public void setPermutations(ArrayList<string> permutations){
this.permutations = permutations;
}
public String getWord(){
return this.word;
}
public ArrayList<String> getPermuatations(){
return this.permuations;
}
}
Step2: Use this class to create your arrayList objects like below:
Class MainPermutation{
public static void main(String args[]){
// your code to get all your words and their permutations
// Now add them like below
ArrayList<WordPermutations> words = new ArrayList<WordPermutations>();
//your loop to iterate words and their permutations
for (int i=0;i<words.length;i++){
WordPermutations wordP = new WordPermutations();
wordP.setWord(word); //String word
wordP.setPermutations(permutations); //arraylist of permutations
words.add(wordP); //adding your word and it's permutations to class
}
}
}
Step3: Now read your arrayList array accordingly
with above process you can store n number of words.
Hope it helps you.
import java.util.ArrayList;
import java.util.Collections;
public class SmartCombining {
public static void main(String[] args) {
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
Collections.addAll(list1, 4, 3);
Collections.addAll(list2, 5, 10, 4, 3, 7);
smartCombine(list1, list2);
System.out.println(list1);
System.out.println(list2);
}
public static void smartCombine(ArrayList<Integer> first,
ArrayList<Integer> second) {
first.addAll(second);
}
}
So, I want to combine two lists into one, but if the second list contains a number from the first it won't be added. So far my method adds them all together.
Well, one way to do it is to iterate through the second list while checking if each element exists in the first list. If it doesn't, add it.
public static void smartCombine(ArrayList<Integer> first, ArrayList<Integer> second) {
for(Integer num : second) { // iterate through the second list
if(!first.contains(num)) { // if first list doesn't contain current element
first.add(num); // add it to the first list
}
}
}
Another way would be for you to hold your values inside a set (like HashSet) which doesn't allow any duplicates. Then you can combine them like:
first.addAll(second);
One more way you could do it is to first remove all elements from the first list that exist in the second list (the ones that would be duplicated). Then you add all elements of the second list to the first list.
public static void smartCombine(ArrayList<Integer> first, ArrayList<Integer> second) {
first.removeAll(second); // remove elements that would be duplicated
first.addAll(second); // add elements from second list
}
The simple, no brains solution:
Set<Integer> joinedSet = new HashSet<Integer>();
joinedSet.addAll(list1);
joinedSet.addAll(list2);
Remove duplicates, then merge both lists:
list1.remove(list2);
list1.addAll(list2);
If you dont want to alter the original list, then first create a backup:
list1BP = new ArrayList(list1);
Another approach is to use HashSet, see other answers.
Use Set, it has been created for that purpose. A Set cannot contain 2 identical elements, based on the equals method.
Set<Integer> list1 = new HashSet<Integer>();
Set<Integer> list2 = new HashSet<Integer>();
Using a combination of ArrayList and contains method is an antipattern here.
There are two easy way you can combine two Lists and duplicate will be removed.
1) First and very easiest way you can get your output, by creating equivalent HashSet object of your ArrayList. Since HashSet does not allow duplicates.
public static void main(String[] args) {
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
Collections.addAll(list1, 4, 3);
Collections.addAll(list2, 5, 10, 4, 3, 7);
System.out.println(smartCombine(list1, list2));
}
public static HashSet<Integer> smartCombine(ArrayList<Integer> first, ArrayList<Integer> second) {
first.addAll(second);
HashSet<Integer> hs = new HashSet<Integer>(first);
return hs;
2) There is another way using advanced for loop. Iterate the second list and check if the current element is not in first list and then add the current element.
public static void main(String[] args) {
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
Collections.addAll(list1, 4, 3);
Collections.addAll(list2, 5, 10, 4, 3, 7);
smartCombine(list1, list2);
System.out.println(list1);
}
public static void smartCombine(ArrayList<Integer> first, ArrayList<Integer> second) {
for (Integer num : second) {
if (!first.contains(num)) {
first.add(num);
}
}
}
Note: The second way will work fine only if first list has no duplicates.
Have you tried ArrayList.addAll()
Look at this java doc
As pointer out this would not handle duplicates which can easily be removed using a Set
use contains(Object) method in ArrayList
public static void smartCombine(ArrayList<Integer> first,
ArrayList<Integer> second) {
for(Integer i :second){
if(!first.contains(i)) { // if first list doesn't contain this item, add item to the first list.
first.add(i);
}
}
}
We are given a list of words in the form of an ArrayList as follows:
public ArrayList<String> getListOfStrings(){
ArrayList<String> list = new ArrayList<String>();
list.add("This");
list.add("is");
list.add("an");
list.add("exercise");
list.add("to");
list.add("illustrate");
list.add("the");
list.add("use");
list.add("of");
list.add("ArrayLists");
list.add(".");
return list;
}
How do I write a method that removes all words in that list (i.e. all the objects in the ArrayList) that have the length "len" entered by the user?
I already wrote a method that lists all the words of length "len" entered by the user, and it works, it's as follows:
public ArrayList<String>getWordsWithLength(int len, ArrayList<String> lijst){
ArrayList<String> list = new ArrayList<String>();
for(String woord: lijst){
if(woord.length()==len){
list.add(woord);
}
}
return(list);
}
But as a beginner in java, I'm stuck on how to remove the words of length "len". Please help!
(I am under the impression that you start by removing them from the end of the list, back-to-front as it were)
The way your currently iterating through the list wont allow you to remove it with an exception but an iterator would.
Iterator<String> it = list.iterator();
while(it.hasNext()) {
if([Condition]) {
it.remove();
}
}
Your method can already serve as a removal, just change the == to a !=
public ArrayList<String> getStringsWithoutEqualLength(int len, ArrayList<String> lijst){
ArrayList<String> list = new ArrayList<String>();
for(String woord: lijst){
if(woord.length() != len){
list.add(woord);
}
}
return(list);
}
If what you are attempting to do is remove the elements from lijst, then just reassign the returned list to it.
ArrayList<String> yourList = ...;
yourList = instance.getStringsWithoutEqualLength(someLength, yourList);
You have effectively removed the longer elements and done it faster than if you had used an Iterator. Every time you remove with an Iterator, you have to resize your backing array.
You have to remove values from a List by using an Iterator to prevent a ConcurrentModificationException.
List<String> myList = getListOfStrings();
Iterator<String> it = myList.iterator();
while (it.hasNext()) {
if(it.next().length() == 3){
it.remove();
}
}
You can even use the same method by adding a boolean parameter.
public ArrayList<String>getWordsWithLength(int len, ArrayList<String> lijst, boolean complement){
ArrayList<String> list = new ArrayList<String>();
for(String woord: lijst){
if((woord.length()==len) != complement){
list.add(woord);
}
}
return(list);
}
If you pass in complement as true, if will give you everything with that doesn't have length == len. complement as false will behave as usual.
While I think that #SotiriosDelimanolis's answer is probably what you should use, I also wanted to point out that with Java 8 you can easily do this using a Stream and a Predicate to filter on:
List<String> list2 = list.stream()
.filter(s -> s.length() != 3)
.collect(Collectors.toList());
Here's a full test class:
import java.util.*;
import java.util.stream.*;
class Test {
public static void main(String args[]) {
ArrayList<String> list = new ArrayList<String>();
list.add("This");
list.add("is");
list.add("an");
list.add("exercise");
list.add("to");
list.add("illustrate");
list.add("the");
list.add("use");
list.add("of");
list.add("ArrayLists");
list.add(".");
System.out.println(list);
List<String> list2 = list.stream()
.filter(s -> s.length() != 3)
.collect(Collectors.toList());
System.out.println(list2);
}
}
and my test output:
$ java Test
[This, is, an, exercise, to, illustrate, the, use, of, ArrayLists, .]
[This, is, an, exercise, to, illustrate, of, ArrayLists, .]
in Scala you'd just do
list.filter(_.length != len)