Two Dimensional ArrayList Java (Gui) - java

I am trying to create program that holds the details of various instruments (e.g. guitars, keyboards). I want it to have information on each item in the Arraylist. I want each instrument to have a Manufacturer and a "description". I am not new to 2D arrays, however i do not know how to use it in Array lists.
I have given it an attempt. (Ps i need to be able to access all of these things to be able to put into a gui. I hope that made sense.)
public class Main {
public static Login form = new Login();
public static ArrayList<ArrayList<String>> instt = new ArrayList<ArrayList<String>>();
public static ArrayList<String> row = new ArrayList<String>();
public static void main(String[] args) {
row.add("Chelo");
row.add("Drums");
row.add("Flute");
row.add("Guitar");
row.add("Harp");
row.add("Piano");
row.add("Recorder");
row.add("Trombone");
row.add("Trumpet");
row.add("Xylophone");
instt.add(row);
form.setVisible(true);
}
}
Any suggestions? Thank you.

The best approach would be to create an Instrument-Class containing all your information.
public static ArrayList<Instrument> row = new ArrayList<Instrument>();
public static void main(String[] args){
row.add(new Instrument("Guitar","Stackoverflow-Instruments","Best guitar!!"));
row.add(new Instrument("Piano","Stackoverflow-Instruments","Best piano!!"));
}
public static class Instrument{
private String name;
private String manufacturer;
private String description;
public String getName() {
return name;
}
public String getManufacturer() {
return manufacturer;
}
public String getDescription() {
return description;
}
public Instrument(String name, String manufacturer, String description) {
this.name = name;
this.manufacturer = manufacturer;
this.description = description;
}
}

Related

Error while mering 2 groups (Im a beginner)

So I have a MusicBand Class and I want to create a method that merges members of 2 different groups into one and clears the empty one.
public class MusicBand {
private int year;
private String name;
private List<String> members;
public MusicBand(String name, int year, List<String> members) {
this.name = name;
this.year = year;
this.members = members;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getMembers() {
return members;
}
public void setMembers(List<String> members) {
this.members = members;
}
public static void transferMembers(MusicBand a, MusicBand b) {
for (String members : a.getMembers()) {
b.getMembers().add(members);
a.getMembers().clear();
}
}
public void printMembers(){
System.out.println(this.members);
}
}
public class Test4 {
public static void main(String[] args) {
List<String> members1 = new ArrayList<>();
members1.add("a");
members1.add("b");
members1.add("c");
List<String>members2 = new ArrayList<>();
members2.add("a2");
members2.add("b2");
members2.add("c2");
MusicBand group1 = new MusicBand("aaa",1990,members1);
MusicBand group2 = new MusicBand("bbb",2010,members2);
group1.printMembers();
group2.printMembers();
MusicBand.transferMembers(group1,group2);
}
}
So it prints out 2 groups and then instead of merging this happens "Exception in thread "main" java.util.ConcurrentModificationException"
What can I do to fix this?
Thanks in advance.
Move your a.getMembers().clear(); method outside your for loop.
In fact your transferMembers() method could look like the following:
public static void transferMembers(MusicBand a, MusicBand b) {
b.getMembers().add(members);
a.getMembers().clear();
}
There is no need for a for loop at all.
It is also bad practice to use a static method for this. So, your MusicBand class should just have a method to add members to it. So, instead of your static transferMembers(...) method you should have these two:
public void addMembers(MusicBand otherBand) {
getMembers().addAll(otherBand.getMembers());
}
public void clear() {
getMembers().clear();
}
You can then decide whether to call clear() from the calling class or inside the addMembers() method.

How to implement a Java Hashmap with different objects as values

I want to parse a YAML-file via Jackson but encounter the problem that one of the properties (let's call it 'Event') has a string called 'type' and a 'properties' object that differs for different Events. My issue is that I need to define the POJOs for this YAML. Therefore, I want to define a Hashmap with VariableObject that can be any of some predefined classes (for brevity, let's say Shipping and Inventory).
How can I implement a Hashmap like that?
public class Event {
private static String type;
private static Map<String, VariableObject> properties;
public static void main(String[] args) {
Inventory inventory = new Inventory("inventoryName", 13);
properties.put("Inventory", inventory);
Shipping shipping = new Shipping("shippingName", true);
properties.put("Shipping", shipping);
}
}
public class Inventory {
private static String name;
private static int someNumber;
public Inventory(String name, int someNumber) {
this.name = name;
this.someNumber = someNumber;
}
}
public class Shipping {
private static String name;
private static boolean someBoolean;
public Shipping(String name, boolean someBoolean) {
this.name = name;
this.someBoolean = someBoolean;
}
}
What you're talking ablut is simple Object. It's the most specific common superclass:
private static Map<String, Object> properties;
Other solution would be to make Inventory and Shipping implement some common interface, for example Named and use it as type parameter in HashMap.
One way to do this is to make Shipping and Inventory implements the same interface (like VariableObject in your cas)
public class Event {
private static String type;
private static Map<String, VariableObject> properties;
public static void main(String[] args) {
Inventory inventory = new Inventory("inventoryName", 13);
properties.put("Inventory", inventory);
Shipping shipping = new Shipping("shippingName", true);
properties.put("Shipping", shipping);
}
}
public interface VariableObject{
//you can define common methods here if you want
}
public class Inventory implements VariableObject{
private static String name;
private static int someNumber;
public Inventory(String name, int someNumber) {
this.name = name;
this.someNumber = someNumber;
}
}
public class Shipping implements VariableObject{
private static String name;
private static boolean someBoolean;
public Shipping(String name, boolean someBoolean) {
this.name = name;
this.someBoolean = someBoolean;
}
}

Why can't I accesses the properties of an object stored in a element of a ArrayList?

I have two packages lets give them the name package 1 and package 2.
Class A and Class B is in package1. Class A contains an ArrayList called PTable. Class B contains a function called query() that filters through PTable,in Class A, based on a certain conditions and returns an ArrayList called result that contains all the elements from PTable that meet that condition.
I now have package2 that contains Class C. Class C imports Class B from package 1; Class C is a subclass of HttpServlet. I create an object of Class B in class C and initializer it.
I then call the function query() and assign it to a variable called results. When I try and get the properties of an element at a certain index, I can't see the properties of the original objects stored in the ArrayList PTable.[This is what appears when I try and access the properties of the objects. My aim is to see the second image ][1]
Nice to ask questions but first spend sometime studying Java. Read a book or online and you will learn about casting very quickly. Also about classes, super classes etc
Your storing the objects in a variable of type Element (your results array list).
Cast the object back to the type it belongs too and then you will see the variables.
Code design note : storing different types of classesin the same array list is legal and possible but bug prone. Try to avoid it. If you change the order of storing variables into the list, you need to change all the access code too. Anyway happy learning.
There are free online Java tutorials study them -> https://www.google.co.in/search?q=java+tutorial+beginner
Sample class, in the main method try to get the object at position 1 and cast it to a Person :
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Car {
private String manufacturer;
private String model;
private double price;
private int yearOfMfr;
private Date dateBought;
private String licenceNumber;
public Car() {
super();
}
public Car(String manufacturer, String model, double price, int yearOfMfr, Date dateBought, String licenceNumber) {
super();
this.manufacturer = manufacturer;
this.model = model;
this.price = price;
this.yearOfMfr = yearOfMfr;
this.dateBought = dateBought;
this.licenceNumber = licenceNumber;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getYearOfMfr() {
return yearOfMfr;
}
public void setYearOfMfr(int yearOfMfr) {
this.yearOfMfr = yearOfMfr;
}
public Date getDateBought() {
return dateBought;
}
public void setDateBought(Date dateBought) {
this.dateBought = dateBought;
}
public String getLicenceNumber() {
return licenceNumber;
}
public void setLicenceNumber(String licenceNumber) {
this.licenceNumber = licenceNumber;
}
}
public class DemoApp {
public static void main(String[] args) {
List<Object> results = new ArrayList<>();
DemoApp app = new DemoApp();
app.fillItUp(results);
Car acar = (Car) results.get(0);
acar.setLicenceNumber("Flying Duck");
}
private void fillItUp(List<Object> results) {
Car car = new Car("sel2in", "electric_VTOL", 540923, 2018, new Date(2018, 3, 32), "Skyprog");
results.add(car);
results.add(new Person("tushar", 39));
}
}

Using Strings from resources in List.

I'm new to Android and I'm having a problem using String variables from resources in my code. I tried a couple of solutions found on the internet and Android API Guides, but they didn't work in this specific case, could also be me not using them correctly.
To be more specific, I have a Master/Detail flow activity and I would like to use resource strings as item names for multilanguage purposes, but I have a problem with recovering actual strings.
The error I get is:
Cannot resolve method 'getString()'
Here is my code based on android studio dummy file
public class Categories {
public static List<CatName> ITEMS = new ArrayList<CatName>();
static {
String temp = getString(R.string.cat_n1);
addItem(new CatName("1", temp);
}
private static void addItem(CatName item) {
ITEMS.add(item);
}
public static class CatName {
public String id;
public String name;
public FieldCat(String id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return name;
}
}}
You need to specify the resource. Try this,
getResources().getString(R.string.cat_n1);
getString(int resId): Return a localized string from the application's package's default string table.
getResources().getString(int id): Returns the string value associated with a particular resource ID. It will be stripped of any styled text information.
Try using it with a constructor passing the context and calling getstring on that
public class Categories {
public static List<CatName> ITEMS = new ArrayList<CatName>();
public Categories(Context ct)
{
String temp = ct.getString(R.string.abc_action_bar_home_description);
addItem(new CatName("1", temp));
}
private static void addItem(CatName item) {
ITEMS.add(item);
}
public static class CatName {
public String id;
public String name;
public CatName(String id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return name;
}
}}

create a class to model a list

I have a class named Person.This class represents (as the name says) a Person. Now I have to create a class PhoneBook to represent a list of Persons. How can I do this? I don't understand what means "create a class to represent a list".
import java.util.*;
public class Person {
private String surname;
private String name;
private String title;
private String mail_addr;
private String company;
private String position;
private int homephone;
private int officephone;
private int cellphone;
private Collection<OtherPhoneBook> otherphonebooklist;
public Person(String surname,String name,String title,String mail_addr,String company,String position){
this.surname=surname;
this.name=name;
this.title=title;
this.mail_addr=mail_addr;
this.company=company;
this.position=position;
otherphonebooklist=new ArrayList<OtherPhoneBook>();
}
public String getSurname(){
return surname;
}
public String getName(){
return name;
}
public String getTitle(){
return title;
}
public String getMailAddr(){
return company;
}
public String getCompany(){
return position;
}
public void setHomePhone(int hp){
homephone=hp;
}
public void setOfficePhone(int op){
officephone=op;
}
public void setCellPhone(int cp){
cellphone=cp;
}
public int getHomePhone(){
return homephone;
}
public int getOfficePhone(){
return officephone;
}
public int getCellPhone(){
return cellphone;
}
public Collection<OtherPhoneBook> getOtherPhoneBook(){
return otherphonebooklist;
}
public String toString(){
String temp="";
temp+="\nSurname: "+surname;
temp+="\nName: "+name;
temp+="\nTitle: "+title;
temp+="\nMail Address: "+mail_addr;
temp+="\nCompany: "+company;
temp+="\nPosition: "+position;
return temp;
}
}
Your PhoneBook class will likely have a member like this:
private List<Person> book = new ArrayList<Person>();
And methods for adding and retrieving Person objects to/from this list:
public void add(final Person person) {
this.book.add(person);
}
public Person get(final Person person) {
int ind = this.book.indexOf(person);
return (ind != -1) ? this.book.get(ind) : null;
}
Note that a List isn't the best possible representation for a phone book, because (in the worst case) you'll need to traverse the entire list to look up a number.
There are many improvements/enhancements you could make. This should get you started.
Based on the class being named PhoneBook, I assume that you ultimately want to create a mapping between a phone number, and a person. If this is what you need to do then your PhoneBook class should contain a Map instead of a List (but this may depend on other parameters of the project).
public class PhoneBook
{
private Map<String,Person> people = new HashMap<String,Person>();
public void addPerson(String phoneNumber, Person person)
{
people.put(phoneNumber,person);
}
public void getPerson(String phoneNumber)
{
return people.get(phoneNumber);
}
}
In the above, the phone number is represented as a String, which is probably not ideal since the same phone number could have different String representations (different spacing, or dashes, etc). Ideally the Map key would be a PhoneNumber class that takes this all into account in its hashCode and equals functions.
you can do it by creating a class PhoneBook
public class PhoneBook{
Private List<Person> personList = new ArrayList<Person>;
public void addPerson(Person person){
this.personList.add(person);
}
public List getPersonList(){
return this.personList;
}
public Person getPersonByIndex(int index){
return this.personList.get(index);
}
}

Categories