import java.util.ArrayList;
public class list {
protected ArrayList<String> a = new ArrayList<String>();
public boolean ad(String aa)
{
boolean t=true;
a.add(aa);
for(String value : courses)
{
if(a.contains(value))
{
a=false;
}
else
{
a=true;
}
}
return a;
}
}
this program should return false if arraylist course contains duplicate elements.else if we are inserting new element return true.
expected output for above code is
true
but it only returns false for any condition.
You can simply utilize ArrayList#contains to verify if an element already exists within the List.
public boolean addCourse(String course) {
if (courses.contains(course)) {
return false;
}
return courses.add(course);
}
You are adding course in the list and then iterating thr the list, so it always gives you true. ArrayList allows duplicates.
if(courses.contains(value))
will always return true as you are adding the course before this in arraylist.
Suggestion: You should use Set than list if you want to avoid duplicates.
Instead of using ArrayList, how about using HashSet to keep your courses ?
http://beginnersbook.com/2013/12/hashset-class-in-java-with-example/
Try the code below:
import java.util.ArrayList;
public class list {
protected ArrayList<String> courses = new ArrayList<String>();
protected String temp = "";
public list(String str, String str2) {
}
public boolean addCourse(String course) {
boolean a = true;
if (courses.isEmpty()) {
courses.add(course);
temp = course;
} else {
if (temp.equalsIgnoreCase(course)) {
a = false;
temp = "";
} else {
a = true;
courses.add(course);
temp = course;
}
}
return a;
}
public static void main(String[] args) {
list inst = new list("John", "WIU");
System.out.println(inst.addCourse("CS560"));
System.out.println(inst.addCourse("CS500"));
}
}
Simple way you can do:
For Each time executing else block so. remove else block it will work.
for(String value : courses)
{
if(courses.contains(value))
{
a=false;
break;
}
a=true;
}
Related
Here is my lab which I am doing
And the code which I write is
package lab.pkg01;
import java.util.*;
public class Lab01 {
public static void main(String[] args) {
String[] L1 = {"Abu Dhabi", "Dubai", "Sharjah", "Ajman"};
String[] L2 = {"Fujara", "Dubai", "Ras Alkhaima", "AlAin"};
MyArrayList list1 = new MyArrayList(L1);
MyArrayList list2 = new MyArrayList(L2);
}
}
class MyArrayList{
static ArrayList<String> MyList = new ArrayList<>();
MyArrayList(String[] list){
for(String i:list){
MyList.add(i);
}
}
public static boolean contains(String e){
boolean b = false;
ArrayList<Integer> positions = new ArrayList<>();
for (int i=0; i<MyList.size(); i++){
if(e == MyList.get(i)){
positions.add(i);
b = true;
}
}
return b;
}
public boolean addAll(MyArrayList e){
for(String s: e){
if(MyList.contains(s)){
MyList.add(s);
} else {
}
}
return true;
}
public boolean removeAll(MyArrayList e){
for(String s: e){
if(!MyList.contains(s)){
MyList.remove(s);
} else {
}
}
return true;
}
#Override
public String toString(){
String s = "";
for (String i : MyList){
s = s+" "+i;
}
return "List: "+s;
}
}
It is giving an error
found: MyArrayList but reuired: array or java.lang object
on addAll() and removeAll() method. Can anyone help me out in resolving this.
Actually What I want to do is to compare Object created in main method to the MyList array so that I can perform addAll() and removeAll() methods.
First of all, you shouldn't be using static for no reason. I don't think you need static for myList and the contains() method in this case.(What does the 'static' keyword do in a class?). Be very careful when using and dealing with static.
Also, Your issue is the for loop. Your Strings are stored in ArrayList myList, from the MyArrayList class. Plus if(MyList.contains(s)) in your addAll() method should be if(!MyList.contains(s)) , because you don't want to add duplicates (I'm assuming it's just your typo.
So instead of for example:
public boolean addAll(MyArrayList e){
for(String s: e){
if(!MyList.contains(s)){
MyList.add(s);
}
}
return true;
}
You should access your string through myList like so:
public boolean addAll(MyArrayList e){
for(String s: e.myList){
if(!MyList.contains(s)){
MyList.add(s);
}
}
return true;
}
Also, as Aman says you should use equals() to compare Strings.
Additionally, your removeAll() and addAll() only returns true, so you may want to fix that as well!
It is better that you don't use static list. Or you have to clear it for every object creation, which is ugly. So, change that first to non static variable.
List<String> myList = new ArrayList<>() instead of ArrayList<String> myList = new ArrayList<>().
In your #contains() method compare String with equals() instead of ==.
AddAll does not seem to work since String is not MyArrayList in for(String s: e) of #addAll() and #removeAll().
public boolean addAll(String[] e){
boolean isChanged = false;
for(String s: e){
if(!myList.contains(s)) {
myList.add(s);
isChanged = true;
}
}
return isChanged;
}
Some modifications on removeAll.
public boolean removeAll(String[] e){
boolean isChanged = false;
for(String s: e){
if(myList.contains(s)) {
myList.remove(s);
isChanged = true;
}
}
return isChanged ;
}
Lastly, try to use Java bean naming style. e.g. ArrayList<String> myList = new ArrayList<>(), myList not MyList.
A playlist is considered a repeating playlist if any of the songs contain a reference to a previous song in the playlist. Otherwise, the playlist will end with the last song which points to null.
I need to Implement a function isRepeatingPlaylist that, returns true if a playlist is repeating or false if it is not.
For example, the following code prints "true" as both songs point to each other.
Song first = new Song("Hello");
Song second = new Song("Eye of the tiger");
first.setNextSong(second);
second.setNextSong(first);
System.out.println(first.isRepeatingPlaylist());
Again, this is not a homework exercise, I am doing coding challenges because when I read theory about programming concepts, I can almost understand, but when faced with writing a program I don't know where to start, or how to apply.
public class Song {
private String name;
private Song nextSong;
public Song(String name) {
this.name = name;
}
public void setNextSong(Song nextSong) {
this.nextSong = nextSong;
}
public boolean isRepeatingPlaylist() {
//throw new UnsupportedOperationException("Waiting to be implemented.");
List<String> list = new ArrayList<String>();
list.add(one);
list.add(two);
list.add(three);
list.add(four);
if list.contains()
return true;
else
return false;
}
public static void main(String[] args) {
Song first = new Song("Hello");
Song second = new Song("Eye of the tiger");
Song third = new Song("a test");
Song fourth = new Song("survivor");
first.setNextSong(second);
second.setNextSong(first);
System.out.println(first.isRepeatingPlaylist();
}
}
You can loop through the playlist and add every song to a set on condition it is not yet in the set. Once you reach the end of the list your list is not a repeating list. If you find a song which exists already in the set, you have a repeating list.
public boolean isRepeatingList(Song firstSong)
{
Set<Song> uniqueSongs=new HashSet<>();
uniqueSongs.add(firstSong);
Song current=firstSong;
while(current.getNextSong()!=null)
{
if(uniqueSongs.contains(current.getNextSong()))
return true;
// add the song to the set, and assign current to the next song
uniqueSongs.add(current=current.getNextSong());
}
// we reached the end of the list without finding any doubles, so:
return false;
}
Please check the answer below:
public boolean isRepeatingPlaylist() {
Song slow = this.nextSong;
Song fast = slow == null ? null : slow.nextSong;
while (fast != null) {
if (slow == this || slow == fast)
return true;
slow = slow.nextSong;
fast = fast.nextSong;
if (fast != null)
fast = fast.nextSong;
}
return false;
}
I think this might work:
public boolean isRepeatingPlaylist()
{
Set<Song> songs = new HashSet<Song>();
songs.add(this);
Song current = this.getNextSong();
//if you did not implment a getter for the nextSong property I think you should
while (current.getNextSong() != null && !songs.contains(current.getNextsong())) {
songs.add(current);
current = current.getNextSong();
}
return songs.contains(current.getNextsong());
}
Edit 1: As mentioned in the comments of this answer, the == in some cases might not be the best because it compares the memory location of each object. In order to fix this issue, implementing the methods hashCode() and equals() are recommended, if you don't know what they are, try reading this.
This problem can be consider the classic problem: linked list has a circle or not.You can find method from here to solve but for your it's not easy to construct linked list,we use another method to solve this problem:count the nextSong,code like this:
public static boolean isRepeatingPlaylist(List<Song> songs) {
int counts = 0;
for (Song song : songs) {
if (null !=song.getNextSong()){
counts ++;
}
}
return songs.size() - counts != 1;
}
The issue with most answers ( esp. one by Conffusion ) is that its not talking about hasCode() & equals(...) method for Song class even though approach is correct. uniqueSongs.contains will not give correct result if these two methods are not properly implemented.
OP has also not shown structure of Song class.
Second thing in code samples of OP is that which class should have which responsibility is not clear & if I already have a custom linkedlist then Java ArrayList won't be needed - though I have added both versions. Use of words - array & arrayList in question title is confusing because OP has a traditional LinkedList & that has noting to do with Java while arrayList is a Java specific DS.
public class Song {
private String data;
private Song nextSong;
public Song(String data) {
this.data=data;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Song getNextSong() {
return nextSong;
}
public void setNextSong(Song nextSong) {
this.nextSong = nextSong;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((data == null) ? 0 : data.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Song other = (Song) obj;
if (data == null) {
if (other.data != null)
return false;
} else if (!data.equals(other.data)) {
return false;
}
return true;
}
}
Ideally , there should be a PlayList class to create playlist and method isRepeatingPlaylist should belong there. I have added in main driver class for simplicity ,
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RepetablePlaylist {
public static void main(String[] args) {
// Begin - construct Song list
Song first = new Song("Hello");
Song second = new Song("Eye of the tiger");
Song third = new Song("a test");
Song fourth = new Song("survivor");
first.setNextSong(second);
second.setNextSong(first);
List<Song> list = new ArrayList<>();
list.add(first);
list.add(second);
list.add(third);
list.add(fourth);
// End - construct Song list
boolean isRepeatable = isRepeatingPlaylist(list);
System.out.println(" isRepeatable : "+isRepeatable);
isRepeatable = isRepeatingPlaylist(first);
System.out.println(" isRepeatable : "+isRepeatable);
}
private static boolean isRepeatingPlaylist(List<Song> playList) {
Set<Song> previous = new HashSet<>();
for(Song song : playList) {
if(song.getNextSong() != null && previous.contains(song.getNextSong())) {
return true;
}
previous.add(song);
}
return false;
}
private static boolean isRepeatingPlaylist(Song head) {
Set<Song> previous = new HashSet<>();
Song currentNode = head;
while(currentNode.getNextSong() != null ) {
if(previous.contains(currentNode.getNextSong())) {
return true;
}
previous.add(currentNode);
currentNode=currentNode.getNextSong();
}
return false;
}
}
I used this code, it will work but the site tells that it is not correct.
Is it ok to add another int member to the class?
public class Song {
private String name;
private Song nextSong;
private int rep = 0 ;
public Song(String name) {
this.name = name;
}
public void setNextSong(Song nextSong) {
this.nextSong = nextSong;
}
public boolean isRepeatingPlaylist() {
if (this.nextSong == null){
return false;
} else {
rep++;
if (rep > 1){
return true;
}
return this.nextSong.isRepeatingPlaylist();
}
}
public static void main(String[] args) {
Song first = new Song("Hello");
Song second = new Song("Eye of the tiger");
first.setNextSong(second );
second.setNextSong(first );
System.out.println(first.isRepeatingPlaylist());
}
}
Please check the answer below:
using System.Collections.Generic;
public bool IsRepeatingPlaylist()
{
HashSet<Song> songs = new HashSet<Song>();
Song current = this;
while (current.NextSong != null && !songs.Contains(current.NextSong))
{
songs.Add(current);
current = current.NextSong;
}
return songs.Contains(current.NextSong);
}
This is my c++ code, it runs greatly!
#include <stdexcept>
#include <iostream>
#include <string>
#include <set>
using namespace std;
class Song
{
public:
Song(std::string name): name(name), nextSong(NULL) {}
void next(Song* song)
{
this->nextSong = song;
}
bool isRepeatingPlaylist()
{
set<string> playlist;
Song *temp=this;
while(temp->nextSong!=NULL){
if (!playlist.insert(temp->name).second) return true;
temp=temp->nextSong;
}
return false;
}
private:
const std::string name;
Song* nextSong;
};
#ifndef RunTests
int main()
{
Song* first = new Song("Hello");
Song* second = new Song("Eye of the tiger");
first->next(second);
second->next(first);
std::cout << std::boolalpha << first->isRepeatingPlaylist();
}
#endif */
Hello guys maybe my doubt is simple but could not solve.
My question is as follows:
I have an ArrayList of objects, these objects have number, name and value.
I would like to sum the values of these objects when the number and name are the same.
I thought of creating a new ArrayList to go the added values sum but to no avail.
My class:
private class ItemAdubacao {
float quantidadeProduto;
String produto;
int tanque_id;
public float getQuantidadeProduto() {
return quantidadeProduto;
}
public void setQuantidadeProduto(float quantidadeProduto) {
this.quantidadeProduto = quantidadeProduto;
}
public String getProduto() {
return produto;
}
public void setProduto(String produto) {
this.produto = produto;
}
public int getTanque_id() {
return tanque_id;
}
public void setTanque_id(int tanque_id) {
this.tanque_id = tanque_id;
}
}
I'm adding objects of this class in an ArrayList.
What I want is to go through this ArrayList checking objects that have Tanque_id and produto equal to sum the quantidadeProduto.
As I said I thought I'd create a new ArrayList and go adding the objects already added. For example:
public void finalizar() {
Adubacao adubacao = new Adubacao();
adubacaoArrayList = new ArrayList<>();
for (ItemAdubacao itemAdubacao : itemAdubacaoArrayList) {
if () {
}
}
adubacaoArrayList.add(adubacao);
}
But do not know how to IF
I solved my question, is not simple question IF
first added boolean equals in my class
public boolean equals(Object o) {
ItemAdubacao adubacao = (ItemAdubacao) o;
if (this.getTanque_id() == adubacao.getTanque_id() && (this.getProduto().equals(adubacao.getProduto()))) {
return true;
}
return false;
}
then I created an ArrayList to separate the duplicate objects and adding the sum of values
public void finalizar() {
ArrayList<ItemAdubacao> itensIguaisArrayList;
itensIguaisArrayList = new ArrayList<>();
adubacaoArrayList = new ArrayList<>();
for (ItemAdubacao itemAdubacao : itemAdubacaoArrayList) {
if (!itensIguaisArrayList.contains(itemAdubacao)) {
itensIguaisArrayList.add(itemAdubacao);
}
}
for (int i = 0; i < itensIguaisArrayList.size(); i++) {
float soma = 0;
for (ItemAdubacao linha : itemAdubacaoArrayList) {
if (linha.equals(itensIguaisArrayList.get(i))) {
soma += linha.getQuantidadeProduto();
}
}
itensIguaisArrayList.get(i).setQuantidadeProduto(soma);
}
}
I am trying to compare a list of type Car that has no equals method.
Car.java
public class Car {
private int carNumber;
private String carName;
public Car(int carNumber, String carName)
{
super();
this.carNumber = carNumber;
this.carName = carName;
}
/**
* #return The carNumber.
*/
public int getCarNumber()
{
return carNumber;
}
/**
* #param carNumber The carNumber to set.
*/
public void setCarNumber(int carNumber)
{
this.carNumber = carNumber;
}
/**
* #return The carName.
*/
public String getCarName()
{
return carName;
}
/**
* #param carName The carName to set.
*/
public void setCarName(String carName)
{
this.carName = carName;
} }
Main class :
import java.util.ArrayList;
import java.util.List;
public class ListCar
{
public static void main (String[] args)
{
Car carList1_a = new Car(1, "Camry");
Car carList1_b = new Car(2, "Corolla");
Car carList1_d = new Car(3, "BMW");
Car carList2_d = new Car(3, "BMW");
Car carList2_a = new Car(2, "Corolla");
Car carList2_b = new Car(1, "Camry");
List<Car> carList1 = new ArrayList<Car>();
carList1.add(carList1_a);
carList1.add(carList1_b);
carList1.add(carList1_d);
List<Car> carList2 = new ArrayList<Car>();
carList2.add(carList2_b);
carList2.add(carList2_d);
carList2.add(carList2_a);
System.out.println(compareLists(carList1, carList2));
}
public static boolean compareLists(List<Car> prevList, List<Car> modelList)
{
if (prevList!= null && modelList!=null && prevList.size() == modelList.size())
{
boolean indicator = false;
for (Car modelListdata : modelList)
{
for (Car prevListdata : prevList)
{
if (prevListdata.getCarName().equals(modelListdata.getCarName()) && prevListdata.getCarNumber() == modelListdata.getCarNumber())
{
return true;
}
if (modelListdata.getCarName().equals(prevListdata.getCarName()))
{
indicator = false;
break;
}
else
{
indicator = true;
}
}
}
if (indicator)
{
return true;
}
}
return false;
}
}
The above method compareLists() does not compare the entire list , I am looking to improvise the method to compare each element of the list of Car type regardless of the order. Without equals method in the Car class.
Any input would be helpful
Thanks !!!
You need to iterate the first List and check that every element is in the second list. If you found an element not found in the second list, the lists are different.
The implementation could be:
public static boolean compareLists(List<Car> prevList, List<Car> modelList)
{
boolean listEquals = true;
if (prevList!= null && modelList!=null && prevList.size() == modelList.size())
{
for (Car modelListdata : modelList)
{
boolean elementInList = false;
for (Car prevListdata : prevList)
{
if (prevListdata.getCarName().equals(modelListdata.getCarName()) && prevListdata.getCarNumber() == modelListdata.getCarNumber())
{
/* The list has the element, set the flag to true and break the loop */
elementInList = true;
break;
}
}
if (elementInList == false) {
/* There is one element not found in the second list, the lists are not equals */
listEquals = false;
break;
}
}
return listEquals;
} else {
/* At least one list is null or the size is not the same */
return false;
}
}
If you implement the equals() and hashCode() methods in your Car class, the code is much more simple as you could use the contains() method of the list:
public static boolean compareListsEquals(List<Car> prevList, List<Car> modelList)
{
if (prevList!= null && modelList!=null && prevList.size() == modelList.size())
{
for (Car modelListdata : modelList)
{
if (prevList.contains(modelListdata) == false) {
return false;
}
}
return true;
} else {
/* At least one list is null or the size is not the same */
return false;
}
}
If you want to see if lists are equal without using equal method for car, then you should:
1. Stop using iterators.
You should be comparing first element with first element. Second with second etc.
You need to use element at the same position in both lists.
It will work given that if lists have different number of elements - it will not be equal.
Using iterators is problematic for that.
2. Check only for not equal elements - in that case return false.
3. At the end of algorithm return true - when each element was checked and passed.
4. Be sure you correctly handles cases with different sizes of list (return false) or when one of them is null (return false) or when both are null (return true).
I hope that helps. Let me know if you need more detailed version with some example.
Check if that return true is a smart thing to do.
[EDIT]
Ok, since it smells like homework I just wanted to give a hint... but here it comes the spoon.
The answer from David is pretty good so I won't reiterate the answer. No pun intended.
I am creating a demo shopping cart in android for this i am using Application class for saving data. I am unable to delete data from linkedlist. I am calling removeItem() function for android activity for removing selected item from the list but it is not working any one can help me.
package in.co.santoshsharma.bookshopping;
import java.util.LinkedList;
import android.app.Application;
import android.content.res.Configuration;
public class GlobalData extends Application{
private String email;
private String itemName;
private int itemQuantity;
private int itemCost;
public GlobalData(){
}
public GlobalData(String iName,int iQunt,int iCost) {
// TODO Auto-generated constructor stub
this.itemCost=iCost;
this.itemName=iName;
this.itemQuantity=iQunt;
}
public void setEmail(String mail)
{
this.email=mail;
}
public String getEmail()
{
return email;
}
public String getItemName()
{
return itemName;
}
public int getItemCost()
{
return itemCost;
}
public int getItemQunt()
{
return itemQuantity;
}
LinkedList<GlobalData> list = new LinkedList<GlobalData>();
public void setList(String iName,int iQunt,int iCost)
{
list.add(new GlobalData( iName, iQunt, iCost));
}
public LinkedList<GlobalData> getList()
{
return list;
}
public void removeItem(String iName,int iQunt,int iCost)
{
for(GlobalData data:list)
{
if(data.getItemName().equals(iName))
{
list.remove(itemName);
//list.remove(iCost);
//list.remove(iQunt);
}
}
}
}
First, override equals() method and use itemName attribute for the comparison
#Override
public boolean equals(Object o) {
if (o == null) return false;
if (itemName == null) return false;
if (o instanceOf String) return itemName.equals(o);
else if (o instanceOf GlobalData) return ((GlobalData) o).itemName.equals(this.itemName);
else return false;
}
Then, change your removeItem() method
public void removeItem(String iName) {
list.remove(iName);
// or uncomment line below to completely remove all matching elements
// for (;;list.remove(iName)) {}
}
According to http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html#remove(java.lang.Object) remove() method of a LinkedList will call the equals() method of the supplied Object and compare it with every element in the list.
Hope this helps :)
you cannot operate in lists (add, remove... items) while you iterate on them. You have to use an Iterator
for(Iterator<EmpDedup> iter = list.iterator(); iter.hasNext();) {
EmpDedup data = iter.next();
if (data.getRecord() == rec1) {
iter.remove();
}
}
see http://docs.oracle.com/javase/6/docs/api/java/util/Iterator.html
Refered from https://stackoverflow.com/a/10735435/1602230
Use a iterator to remove the element:
public void removeItem(String iName, int iQunt, int iCost) {
Iterator<GlobalData> iterator = list.iterator();
while (iterator.hasNext()) {
GlobalData data = iterator.next();
if (data.getItemName().equals(iName)) {
iterator.remove();
}
}
}
- You are Concurrently accessing and modifying the Collection, that can't be done from For-Each loop directly..
- Use Iterator to solve this problem.
LinkedList<GlobalData> q1 = new LinkedList<GlobalData>();
Iterator<GlobalData> iterator = q1.iterator();
while (iterator.hasNext()){
GlobalData mp = iterator.next();
if (mp.name.equals("xyz")){
iterator.remove(); // You can do the modification here.
}
}
You cannot modify a Collection using for-each loop. Use simple for loop or while.
The for-each loop hides the iterator, so you cannot call remove.
Therefore, the for-each loop is not usable for filtering. Similarly it
is not usable for loops where you need to replace elements in a list
or array as you traverse it.
Source: http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
Generally, a collection named list storing elements of type E uses an iterator in the following way:
Iterator<E> iterator = list.iterator();
while(iterator.hasNext()) {
<do something with iterator.next()>;
}