This question already has answers here:
Avoiding overwriting objects in ArrayList
(2 answers)
Closed 3 years ago.
The data which was previously stored in an array list , is getting replaced by updated data.
code is shown below
public class Telivision {
private String tvBrand;
private Double tvCost;
private Integer tvDimension;
private String tvScreen;
public String getTvBrand() {
return tvBrand;
}
public void setTvBrand(String tvBrand) {
this.tvBrand = tvBrand;
}
public Double getTvCost() {
return tvCost;
}
public void setTvCost(String brand) {
if(this.tvBrand.equalsIgnoreCase("Samsung")){
this.tvCost = 100*1.5;
}else if(this.tvBrand.equalsIgnoreCase("Sony")){
this.tvCost = 100*2.0;
}
}
public Integer getTvDimension() {
return tvDimension;
}
public void setTvDimension(Integer tvDimension) {
this.tvDimension = tvDimension;
}
public String getTvScreen() {
return tvScreen;
}
public void setTvScreen(String tvScreen) {
this.tvScreen = tvScreen;
}
#Override
public String toString() {
return "Telivision [tvBrand=" + tvBrand + ", tvCost=" + tvCost + ", tvDimension=" + tvDimension + ", tvScreen="
+ tvScreen + "]";
}
TESTER IS AS SHOWN BELOW
public class TelivisionTester {
public static void main(String[] args) {
Telivision telivision = new Telivision();
ArrayList<Telivision> telList = new ArrayList<Telivision>();
telivision.setTvBrand("SAMSUNG");
telivision.setTvDimension(40);
telivision.setTvScreen("Led");
telivision.setTvCost("Samsung");
telList.add(telivision);
System.out.println(telList);
System.out.println(telivision.getTvBrand()+"Cost is "+telivision.getTvCost());
telivision.setTvBrand("Sony");
telivision.setTvDimension(36);
telivision.setTvScreen("Led");
telivision.setTvCost("Sony");
telList.add(telivision);
System.out.println(telList);
System.out.println(telivision.getTvBrand()+"Cost is "+telivision.getTvCost());
}
the output which is expected is as shown below
[Telivision [tvBrand=SAMSUNG, tvCost=150.0, tvDimension=40, tvScreen=Led],
Telivision [tvBrand=Sony, tvCost=200.0, tvDimension=36, tvScreen=Led]]
but the output observed is as shown below
[Telivision [tvBrand=Sony, tvCost=200.0, tvDimension=36, tvScreen=Led],
Telivision [tvBrand=Sony, tvCost=200.0, tvDimension=36, tvScreen=Led]]
kindly let me know what mistake i am doing in this code
You're list is not being overwritten. You are are adding the same instance of the class twice instead of creating a new one with the new attributes. Because the original istance changed you get the same attributes for both entries in the list. Create a new instance of the object for each Television you add to the list.
public static void main(String[] args) {
Telivision telivision = new Telivision();
ArrayList<Telivision> telList = new ArrayList<Telivision>();
telivision.setTvBrand("SAMSUNG");
telivision.setTvDimension(40);
telivision.setTvScreen("Led");
telivision.setTvCost("Samsung");
telList.add(telivision);
System.out.println(telList);
System.out.println(telivision.getTvBrand()+"Cost is "+telivision.getTvCost());
Telivision secondTelivision = new Telivision();
secondTelivision.setTvBrand("Sony");
secondTelivision.setTvDimension(36);
secondTelivision.setTvScreen("Led");
secondTelivision.setTvCost("Sony");
telList.add(secondTelivision);
System.out.println(telList);
}
You forgot to declare a second Telivision to separate the two.
public class TelivisionTester {
public static void main(String[] args) {
Telivision telivision = new Telivision();
ArrayList<Telivision> telList = new ArrayList<Telivision>();
telivision.setTvBrand("SAMSUNG");
telivision.setTvDimension(40);
telivision.setTvScreen("Led");
telivision.setTvCost("Samsung");
telList.add(telivision);
System.out.println(telList);
System.out.println(telivision.getTvBrand()+"Cost is "+telivision.getTvCost());
Telivision television2 = new Television();
telivision2.setTvBrand("Sony");
telivision2.setTvDimension(36);
telivision2.setTvScreen("Led");
telivision2.setTvCost("Sony");
telList.add(telivision2);
System.out.println(telList);
System.out.println(telivision2.getTvBrand()+"Cost is "+telivision2.getTvCost());
//telList.addAll(telList);
//System.out.println(telList);
}
}
Also “Telivision” is actually spelled Television
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Create a class that acts as the Parent class to each of these TV Show
types: Family, Comedy, Dark, Mystery, Other.
Each type of TV Show shall inherit from that Parent class.Determine
what data and methods exist in the Parent and what exists in each
childThere should be two constructors per child class. In the main()
program, store all the TV Shows in an ArrayListUse a while
loop to ask the user what show they want to ask a question of then
answer questions that pertain to the TV Show. Use the ArrayList to
answer the questions. Provide the capability to the user to display
all the TV Shows and the respective data.
So far I have managed to write a superclass and subclasses for each type of show and store the TV shows in an Array List. I am stuck on everything else.
A sample of the tvShowData.csv:
Title,audience ,network,actor 1,actor 2,actor 3,actor 4,TV Show Type
The Walking Dead,11.24,AMC,Norman Reedus,Andrew Lincoln,Lauren Cohan,Steven Yeun,Dark
Teen Wolf,3.02,MTV,Dylan O'Brien,Tyler Posey,Holland Roden,Tyler Hoechlin,Dark
Scanner keyboard = new Scanner(System.in);
String file = "tvshowData.csv";
List<List<String>> tvShows = new ArrayList<>();
String line;
String userInput;
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
while ((line = br.readLine()) != null) {
String[] shows = line.split(",");
tvShows.add(Arrays.asList(shows));
}
System.out.println(tvShows);
}
System.out.println("Enter the TV Show you want to know about:");
userInput = keyboard.nextLine();
// Superclass
public class TVShows
{
private String title;
private double audience;
private String network;
private String actor1, actor2, actor3, actor4;
public TVShows(String title, double audience, String network)
{
this.title = title;
this.audience = audience;
this.network = network;
}
public TVShows(String actor1, String actor2, String actor3, String actor4)
{
this.actor1 = actor1;
this.actor2 = actor2;
this.actor3 = actor3;
this.actor4 = actor4;
}
public String getTitle()
{
return title;
}
public double getAudience()
{
return audience;
}
public String network()
{
return network;
}
public String getActor1()
{
return actor1;
}
public String getActor2()
{
return actor2;
}
public String getActor3()
{
return actor3;
}
public String getActor4()
{
return actor4;
}
}
// Subclass
public class Dark extends TVShows
{
private String tvShowType;
public Dark(String nameOfShow, double audience, String network)
{
super(nameOfShow, audience, network);
}
public Dark(String actor1, String actor2, String actor3, String actor4)
{
super(actor1, actor2, actor3, actor4);
}
public void setTvShowType(String tvShowType)
{
this.tvShowType = tvShowType;
}
public String getTvShowType()
{
return tvShowType;
}
}
Mainly you could use something like, but you have to adapt with your inputs.
Matching is based on using various predicates
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
test();
}
public static void test() {
//prepare data, here is just something for test
List<String> lst1 = Arrays.asList("A", "B", "C", "B", "B");
List<String> lst2 = Arrays.asList("A", "D", "E");
ShowData sd1 = new Test().new ShowData("show1", lst1);
ShowData sd2 = new Test().new ShowData("show2", lst2);
// System.out.println(sd1);
ShowList<ShowData> sl = new Test().new ShowList<ShowData>();
sl.add(sd1);
sl.add(sd2);
//write searching criteria
Predicate<String> pactorA = t -> t.equals("A");
Predicate<ShowData> haveActorA = t -> t.actors.stream().filter(pactorA).count() > 0;
System.out.println("[Count Lines for Actor A]=" + sl.stream().filter(haveActorA).count());
//use criteria and print any matching-lines
sl.stream().filter(haveActorA).forEach(System.out::println);
//same as above but with other criteria[another actor]
Predicate<String> pactorB = t -> t.equals("B");
Predicate<ShowData> haveActorB = t -> t.actors.stream().filter(pactorB).count() > 0;
System.out.println("[Count Lines for Actor B]=" + sl.stream().filter(haveActorB).count());
sl.stream().filter(haveActorB).forEach(System.out::println);
Predicate<String> pactorF = t -> t.equals("F");
Predicate<ShowData> haveActorF = t -> t.actors.stream().filter(pactorF).count() > 0;
System.out.println("[Count Lines for Actor F]=" + sl.stream().filter(haveActorF).count());
sl.stream().filter(haveActorF).forEach(System.out::println);
}
#SuppressWarnings("hiding")
class ShowList<ShowData> extends ArrayList<ShowData> {
private static final long serialVersionUID = 1L;
}
class ShowData {
String name;
List<String> actors = new ArrayList<>();
public ShowData(String name, List<String> actor) {
this.name = name;
this.actors.addAll(actor);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getActors() {
return actors;
}
public void setActors(List<String> actors) {
this.actors = actors;
}
public String toString() {
return "name=" + name + " and actors=[" + actors.stream().collect(Collectors.joining(",")) + "]";
}
}
}
Output:
[Count Lines for Actor A]=2
name=show1 and actors=[A,B,C,B,B]
name=show2 and actors=[A,D,E]
[Count Lines for Actor B]=1
name=show1 and actors=[A,B,C,B,B]
[Count Lines for Actor F]=0
Its not compiling and i have no idea why... New to sqlite and tried to follow some question's answer on stack overflow but not able to figure it out. Modal class is MainDataHelper
Code
MainDataHelper myDatabaseHelper = new MainDataHelper(getActivity());
myDatabaseHelper.openDataBase();
String text = myDatabaseHelper.getMostMessagesSent(); //this is the method to query
myDatabaseHelper.close();
mMostMessagesSent.setText(text);
mMostMessagesSent.setTextColor(Color.WHITE);
Helper
public class MainDataHelper extends Activity {
private int TotalMessagesSent;
private int TotalMessagesRecieved;
private int TotalMessages;
private String TotalTimeSpent;
private String MostMessagesSent;
private String MostMessagesRecieved;
private String MostTexted;
private String MostTimeSpent;
private int QuizTaken;
private int QuizTakers;
private int Reviewed;
private int Reviews;
public MainDataHelper() {
TotalMessagesSent = 0;
TotalMessagesRecieved = 0;
TotalMessages = 0;
TotalTimeSpent = "";
MostMessagesSent = "";
MostMessagesRecieved = "";
MostTexted = "";
MostTimeSpent = "";
QuizTaken = 0;
QuizTakers = 0;
Reviewed = 0;
Reviews = 0;
}
public MainDataHelper( int TotalMessagesSent, int TotalMessagesRecieved, int TotalMessages, String TotalTimeSpent,String MostMessagesSent, String MostMessagesRecieved, String MostTexted, String MostTimeSpent,int QuizTaken, int QuizTakers, int Reviewed, int Reviews) {
TotalMessagesSent = TotalMessagesSent;
TotalMessagesRecieved = TotalMessagesRecieved;
TotalMessages = TotalMessages;
TotalTimeSpent = TotalTimeSpent;
MostMessagesSent = MostMessagesSent;
MostMessagesRecieved = MostMessagesRecieved;
MostTexted = MostTexted;
MostTimeSpent = MostTimeSpent;
QuizTaken = QuizTaken;
QuizTakers = QuizTakers;
Reviewed = Reviewed;
Reviews = Reviews;
}
public int getTotalMessagesSent() {
return TotalMessagesSent;
}
public int getTotalMessagesRecieved() {
return TotalMessagesRecieved;
}
public int getTotalMessages() {
return TotalMessages;
}
public String getTotalTimeSpent() {
return TotalTimeSpent;
}
public String getMostMessagesSent() {
return MostMessagesSent;
}
public String getMostMessagesRecieved() {
return MostMessagesRecieved;
}
public String getMostTexted() {
return MostTexted;
}
public String getMostTimeSpent() {
return MostTimeSpent;
}
public int getQuizTaken() {
return QuizTaken;
}
public int getQuizTakers() {
return QuizTakers;
}
public int getReviewed() {
return Reviewed;
}
public int getReviews() {
return Reviews;
}
public void setTotalMessagesSent(int TotalMessagesSent) {
TotalMessagesSent = TotalMessagesSent;
}
public void setTotalMessagesRecieved(int TotalMessagesRecieved) {
TotalMessagesRecieved = TotalMessagesRecieved;
}
public void setTotalMessages(int TotalMessages) {
TotalMessages = TotalMessages;
}
public void setTotalTimeSpent(String TotalTimeSpent) { TotalTimeSpent = TotalTimeSpent; }
public void setMostMessagesSent(String MostMessagesSent) {
MostMessagesSent = MostMessagesSent;
}
public void setMostMessagesRecieved(String MostMessagesRecieved) {
MostMessagesRecieved = MostMessagesRecieved;
}
public void setMostTexted(String MostTexted) {
MostTexted = MostTexted;
}
public void setMostTimeSpent(String MostTimeSpent) { MostTimeSpent = MostTimeSpent; }
public void setQuizTaken(int QuizTaken) {
QuizTaken = QuizTaken;
}
public void setQuizTakers(int QuizTakers) {
QuizTakers = QuizTakers;
}
public void setReviewed(int Reviewed) { Reviewed = Reviewed; }
public void setReviews(int Reviews) {
Reviews = Reviews;
}
}
......................................................................................................................................................................................................................
It's not compiling due to a few reasons.
First MainDataHelper does not have a constructor that accepts/takes an Activity. MainDataHelper has two constructors one takes no parameters, the other takes 12 parameters. You have to use one of the available constructors when instantiating a MainDataHelper object.
e.g. MainDataHelper myDatabaseHelper = new MainDataHelper(); would compile.
There is no openDatabase method in MainDataHelper, you would either have to add such a method or do away with the line myDatabaseHelper.openDataBase();
There is no close method in MainDataHelper, you would either have to add such a method or do away with the line myDatabaseHelper.close();
Considering that you want to use an SQLite database then you will use a sub-class of the SQLiteOpenHelper class that would be invoked from an Activity or a Fragment (or even many of these).
Before even considering writing a line of code you would need to understand you requirements for the database and have some sort of design (schema). Ignoring that and assuming (for demonstration) that you want a simple database with one table called questions and has one column called question then the following could be such a class (in this case MainDataBaseHelper.java) :-
public class MainDatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASENAME = "question.db"; //<<<<<<<<<< name of the database
public static final int DATABASEVERSION = 1; //<<<<<<<<<< version number of the database
public static final String TABLE_QUESTION = "question"; //<<<<<<<<<< name of the quiz table
public static final String COLUMN_QUESTION_QUESTION = "question";
public MainDatabaseHelper(Context context) {
super(context, DATABASENAME, null, DATABASEVERSION);
}
//<<<<<<<<<< Called ONCE when the database is first created (first time an attempt is made to open if)
#Override
public void onCreate(SQLiteDatabase db) {
String crt_questiontable_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUESTION + "(" +
COLUMN_QUESTION_QUESTION + " TEXT" +
")";
db.execSQL(crt_questiontable_sql);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long addQuestion(String question) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_QUESTION_QUESTION,question);
return this.getWritableDatabase().insert(TABLE_QUESTION,null,cv);
}
public Cursor getAllQuestions() {
return this.getWritableDatabase().query(TABLE_QUESTION,null,null,null,null,null,null);
}
}
With the above class existing your code could then be (as a simple example) :-
MainDatabaseHelper myDBHlpr = new MainDatabaseHelper(getActivity()); // Instantiate a MainDatabasehelper object called myDBHlpr
// Add some questions to the questions table
myDBHlpr.addQuestion("This is the first question");
myDBHlpr.addQuestion("This is another question");
myDBHlpr.addQuestion("Yet another question");
// Now get all of the questions
Cursor csr = myDBHlpr.getAllQuestions();
Log.d("DBINFO","There are " + String.valueOf(csr.getCount()) + " questions in the database.");
// Loop through all the questions
while (csr.moveToNext()) {
Log.d("DBINFO",
"Question " +
String.valueOf(csr.getPosition() + 1) +
" is " + csr.getString(csr.getColumnIndex(MainDatabaseHelper.COLUMN_QUESTION_QUESTION))
);
mMostMessagesSent.setText(csr.getString(csr.getColumnIndex(MainDatabaseHelper.COLUMN_QUESTION_QUESTION));
}
csr.close(); //<<<<<<<<<< Should always close Cursor when done with it.
//mMostMessagesSent.setText(text); //<<<<<<<<<< done in the loop through the cursor (for demonstration very likely only the last question will be seen)
mMostMessagesSent.setTextColor(Color.WHITE);
When run (for the first time) the log would then include :-
11-12 20:17:16.345 1376-1376/? D/DBINFO: There are 3 questions in the database.
11-12 20:17:16.345 1376-1376/? D/DBINFO: Question 1 is This is the first question
11-12 20:17:16.345 1376-1376/? D/DBINFO: Question 2 is This is another question
11-12 20:17:16.345 1376-1376/? D/DBINFO: Question 3 is Yet another question
Additionally the last question (which may or may not be the last question added) will be displayed in the TextView.
Note 3 rows would be added to the table each time the above is run.
Note this is purely intended as an introduction/demonstration there is a great deal more that needs to be done, such as designing the database.
I have created a class like this, which contains a bunch of arraylist as you can see. I've been setting the array with the methods add.. and then retrieving it with get.., when i tried to System.out.println numberofcitizen for example it is returning 0. Note that i have instantiated the class in another class to set the values.
public int numberOfCitizen;
private final ArrayList<Integer> citizenid = new ArrayList<>();
private final ArrayList<String> citizenName = new ArrayList<>();
private final ArrayList<Integer> citizenWaste = new ArrayList<>();
private final ArrayList<Float> longitude = new ArrayList<>();
private final ArrayList<Float> latitude = new ArrayList<>();
private final ArrayList<String> address = new ArrayList<>();
public void working() {
System.out.println("executing fine");
}
public void setnoOfcit(int number) {
this.numberOfCitizen = number;
}
public int getnumber() {
return this.numberOfCitizen;
}
public void addCitizenId(int citizen) {
citizenid.add(citizen);
}
public int getCitizenid(int i) {
int citId = citizenid.get(i);
return citId;
}
public void addCitizenName(String citizenname) {
citizenName.add(citizenname);
}
public String getCitizenName(int i) {
return citizenName.get(i);
}
public void addCitizenWaste(int waste) {
citizenWaste.add(waste);
}
public int getCitizenWaste(int i) {
return citizenWaste.get(i);
}
public void addLatitude(float lat) {
latitude.add(lat);
}
public float getLat(int i) {
return latitude.get(i);
}
public void addlng(float lng) {
longitude.add(lng);
}
public float getlng(int i) {
return longitude.get(i);
}
com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.Builder vrpBuilder = com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.Builder.newInstance();
public void runVPRSolver() {
System.out.println(numberOfCitizen);
System.out.println(getCitizenName(0));
//create a loop to fill parameters
Probable source of problem :
numberOfCitizen is a member attribute that you seem to never change. If you want it to represent the number of elements in your lists, either use citizenName.size() or increment the value of numberOfCitizen in one of the add methods.
Design flaw :
Your design takes for granted that your other class always use that one properly. Anytime you or someone uses that class, he must make sure that he add every single element manually. This adds code that could be grouped inside your class, which would be cleaner and easier to maintain.
So instead of several add method like this :
addCitizenid();
addCitizenName();
addCitizenWaste();
addLongitude();
addLatitude();
addAddress();
Design an other Citizen class which will contain those elements, and use a single list of instances of that class. That way you can use only one method :
private List<Citizen> citizenList = new ArrayList<>();
public void addCitizen(Citizen c) {
/*Add element in your list*/
citizenList.add(c);
}
This programming methodology is called "Encapsulation" which you can read about here
You need to increment numberOfCitizen in your add methods. For example:
public void addCitizenId(int citizen){
citizenid.add(citizen);
numberOfCitizen++;
}
I would also suggest encapsulating your variables into Objects, so create a citizen class:
public class Citizen {
private Integer id;
private Integer name;
private Integer waste;
}
And change your variable to an ArrayList of objects:
ArrayList<Citizen> citizens;
This question already has an answer here:
Get object name in Java [closed]
(1 answer)
Closed 7 years ago.
I would like to know if we can get the name of instance name in Java. For example:
class A {
public void run() {
System.out.println("Name: " + ????);
}
}
public class Main
{
public static void main(String[] _args) {
A p = new A();
A q = new A();
p.run();
q.run();
}
}
My expectation result would be:
Name: p
Name: q
Is it anyway to get this?
That's impossible in Java, not even available through reflection. Your best bet is you have a String field where you will store the name of the variable and fill this field when creating the object reference.
class A {
private final String name;
public A(String name) {
this.name = name;
}
public void run() {
System.out.println("Name: " + this.name);
}
}
//...
A p = new A("p");
A q = new A("q");
I have class which initiates an arraylist of type String. I then add some dummy data into this array.
public class Main {
public static void main(String[] args)
{
Home h = new Home();
h.add();
}
}
public class Home
{
public ArrayList<String> Group_Customers= new ArrayList<String>();
public void add()
{
String[] group1 = {"0", "Mr", "Smith", "Andrew"}
for(int i = 1; i < group1.length; i++)
{
Group_Customers.add(group1[i]);
}
Add_Booking a = new Add_Booking();
a.Add();
}
}
In a seperate class. I then call this arraylist and add more data to it. However the array is empty in this different class
public class Add_Booking
{
String Title;
String Firstname;
String Surname;
public void add_Data
{
Title = "Mr";
Firstname = "Bob";
Surname = "Gallow";
save_Data();
}
public void save_Data
{
Home h = new Home();
String[] responses = {Title, Firstname, Surname};
for(int i = 1; i < responses.length; i++)
{
h.Group_Customers.add(responses[i]);
}
System.out.println(h.Group_Customers);
}
}
--Outputs responses without group1 test from class Home.
Am I refering to Group_Customers wrong within this different class?
All help appreciated.
Thanks
When calling Home h = new Home(); you instantiate a new Home with the default constructor.
Make sure you add the dummy data in the constructor if you want the array to contains data. Also, the actual code would not compile, you can't just throw method call in class body.
You would have something like this :
public class Home
{
//Declare the List
public ArrayList<String> Group_Customers = null;
//Default constructor
public Home()
{
//Instantiate and add dummy data
Group_Customers = new ArrayList<String>();
Group_Customers.add("test");
}
}
public class Add_Booking
{
public static void main(String args[])
{
//Construct a new home with default constructor.
Home h = new Home();
//Add new data
h.Group_Customers.add("new data");
//Display List content (should display test and new data)
System.out.println(h.Group_Customers);
}
}
Note that by convention, variable should start with a lower-case and an upper-case at each words so you should rename your variable as groupCustomers.