Adding items to ArrayList with separation - java

I'm doing a project on web scraping using ArrayLists. When I scrape the info, it comes back as item [0] = pencil, item [1] = $1.50. I would like these items to be together, or if possible it would be even better if the prices and item each had their own id, but each was somehow linked together so that I could reference each one separately. Also, sometimes when scraping I get item [2] = paper, item [3] = $5.00, item [4] = wide bound college ruled, where item [4] represents an optional description that was included with the item that would need to be included in the ArrayList or in a separate ArrayList linked by ids as before. Any ideas are appreciated.

If you only need the name and the price, your best solution is to use a Map, works kind of like an ArrayList<T>, but instead of a single element you have a couple <Key,Value>, like <pencil, 1,50>.
If you need more than two values I would suggest to create your own class, for example:
public class Item {
private String name;
private double price;
private String description;
}
With all the extra methods you need, then declare your ArrayList like this;
ArrayList<Item> items = new ArrayList<>()

It would be better to make a class Item width variables for your name, price and description.
Then you can make an ArrayList to store all of your items.

You should model the object as a class, for example "item", and add each value as a variable of the class. For example:
public class item{
private String name;
private double price;
private String description; //If there's no description it could be null
// Constructor
...
// Getters and setters
...
}
You will need to format the price as a double.

Related

give value to items of spinner and use them in calculation

I'm designing an app that has 4 spinners a text view and a button and according to what they choose it calculates price of translation service.
I want to know how to assign value to an item in spinner and then use it in calculation.
For example one of the items is English so I want to give value 2 so when that person clicks on English value 2 be used in a formula like below.
Result = Value of item selected in spinner 1 * Value of item selected in spinner 2 *Value of item selected in spinner 3 *Value of item selected in spinner 4
Any hint would be useful
The best way is as below:
1. Make a custom Class
class MyClass {
public int Id;
public String Title;
public long Price;
public MyClass (int id,String title,long price){
Id = id;
Title = title;
Price = price;
}
#Override
public String toString() {
return Title;
}
}
2. Use Array Adapter for the spinner with custom model:
new ArrayAdapter<MyClass>(getApplicationContext(),
android.R.layout.simple_dropdown_item_1line, YOUR_LIST_OF_ITEMS);
3. Whenever you want to get the selected item, just do this:
((MyClass)YOUR_SPINNER.getSelectedItem()).Id
by this way you can have access to any parameter in your model.
Important Note :
Do not forget to override toString method in your custom class. that is the method to show title in the spinner.
By using this approach, you would not need to set any listener listener or hold a reference to selected item.
EDIT : use string instead of any custom class
If you want to use string array that is ok. At the end when you are getting the selected item, just search in the array and find the index and use that.
String selectedItem = YOUR_SPINNER.getSelectedItem().toString();
int index = YOUR_STRING_ARRAY_LIST.indexOf(selectedItem);

getting the holder of an arrayList

I have a Course class which has a method to add Items, which can be a note, an assignment, a URL, or just a generic item. All Items are kept in an ArrayList which the Course that created the list keeps up with. My question is from an item inside this ArrayList, how do I get the printLogger that I have attached to the course object in order to attach it to an item when the Item is created?
this from my Course:
public class Course {
private ArrayList<Item> items;
public PrintLogger p1 = null;
public Course(String code, String name) {
this.code = code;
this.name = name;
items = new ArrayList<>();
}
void add(Item item) {
items.add(item);
if (hasPrintLogger() == true) {
log(PrintLogger.INFORMATIONAL, "Adding " + item.toString());
}
}
And Im trying to have in the code that the assignment constructor runs a way to attach the same printLogger that is already on the course.
You could store a reference to the proper Course object in each of the items in the List.
You could also wrap the ArrayList class in your own class and add a field that points to the Course it belongs to if you need it to be a relationship between the List and the Course instead of between the items in the List and the Course.
You could also search each Course object in your system and check if it contains the List in question. However, this solution would scale badly.

Java: creating several instances of object in class itself or how to restructure

I'm a java beginner and have a question concerning how to best structure a cooking program.
I have a class called Ingredient, this class currently looks like this:
public class Ingredient {
private String identifier;
private double ingredientFactor;
private String titleInterface;
public Ingredient(String identifier, double ingredientFactor,String titleInterface) {
this.identifier = identifier;
this.ingredientFactor = ingredientFactor;
this.titleInterface = titleInterface;
}
I want to initialize several objects (about 40) with certain values as instance variables and save them in a Map, for example
Map<String, Ingredient> allIngredients = new HashMap<String, Ingredient>();
allIngredients.put("Almonds (ground)", new Ingredient("Almonds (ground)", 0.7185, "Almonds (ground)");
Later on I want to retrieve all these objects in the form of a Map/HashMap in a different class.
I'm not sure how to proceed best, initialize all these objects in the Ingredient class itself or provide a method that initializes it or would it be better to create an super class (AllIngredients or something like that?) that has a Map with Ingredients as instance variables?
Happy for any suggestions, thanks in advance :)
Please do not initialize all these objects in the Ingredient class itself. That would be a bad practice for oops.
Just think your class is a template from which you create copies(objects) with different values for attributes. In real world if your class represent model for a toy plane which you would use to create multiple toy planes but each bearing different name and color then think how such a system would be designed. You will have a model(class). Then a system(another class) for getting required color and name from different selection of colors and names present(like in database,files,property file ) etc.
Regarding your situation .
If predetermined values store the values in a text file,properties file,database,constants in class etc depending on the sensitivity of the data.
Create Ingredient class with constructors
Create a class which will have methods to initialize Ingredient class using predetermined values,update the values if required,save the values to text file -database etc and in your case return as map .
Also check the links below
http://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm
http://www.oracle.com/technetwork/java/dataaccessobject-138824.html
Sounds to me like you are looking for a static Map.
public class Ingredient {
private String identifier;
private double ingredientFactor;
private String titleInterface;
public Ingredient(String identifier, double ingredientFactor, String titleInterface) {
this.identifier = identifier;
this.ingredientFactor = ingredientFactor;
this.titleInterface = titleInterface;
}
static Map<String, Ingredient> allIngredients = new HashMap<String, Ingredient>();
static {
// Build my main set.
allIngredients.put("Almonds (ground)", new Ingredient("Almonds (ground)", 0.7185, "Almonds (ground)"));
}
}

Java - Search HashSet for field of object

I am teaching myself Java and I have a simple package with three classes - shop, product and shelf. A shop object contains many shelves, and a shelf contains many products, and, in this case, each product is only available on one shelf.
A product looks like this:
public class t_product {
private t_shelf shelf;
private String name;
}
And a shelf looks like this:
public class t_shelf {
private Set<t_product> products = new HashSet<>();
private String name;
}
The shop object looks like this:
public class t_shop {
private Set<t_shelf> shelves = new HashSet<>();
}
I also have a set of functions which will add or remove a product from the shelf.
myshelf.addProduct(myproduct);
will set myproduct.shelf = myshelf, and add myproduct to myshelf.products. This works fine, and handles the relationship nicely. Similar functions link shop and shelves.
Moving on to the problem
I have a .csv which stores:
Product | Shelf
----------------------
Hats | Headwear
Helmets | Headwear
Socks | Footwear
Apples | Fruit
Bananas | Fruit
Oranges | Fruit
When parsing the .csv, I want to search for the shelf by name to see if it has already been created, so, for example, on reading a line "Bananas, Fruit", it would process:
if (!myshop.getShelfByName("Fruit")){
myshop.addShelf(new t_shelf("Fruit"));
}
myshop.getShelfByName("Fruit").addProduct("Bananas"); //Constructors accept the name as a parameter.
My question is:
Is there a neater implementation of getShelfByName(String name) than simply iterating through the HashSet and checking for the name against every single item? (Want to avoid O(N) algorithms).
Thanks!
Any attempt to solve this VERY gratefully received :)
If you're creating classes of objects to be held in a HashSet, you must give these classes decent equals() and hashCode() override methods, ones that make sense and that play well together (that for one use the same invariant fields to determine their results).
As for your specific question, consider putting things in HashMaps rather than HashSets, as then you can easily find the object by its key.
You should store your shelves in a HashMap (the key should be the name of the shelve).
You will have a O(1) algorithm.
public class t_shop {
private Map<String, t_shelf> shelves = new HashMap<String, t_shelf>();
public void addShelve(t_shelf) {
shelves.put(t_shelf.getName(), t_shelf);
}
public tshelf getShelfByName(String name) {
return shelves.get(name);
}
}
t_shelf shelf = myshop.getShelfByName("Fruit");
if (null != shelf){
shelf = new t_shelf("Fruit");
myshop.addShelf(shelf);
}
shelf.addProduct("Bananas");
Using a HashMap instead of a Set would make looking for a named shelf trivial:
private Map<String, t_shelf> shelves = new HashMap<>();
// ...
if (shelves.contains(name)) {
t_shelf shelf = shelves.get(name);
shelf.addProduct(product);

Deleting from ArrayList Java

I'm trying to delete an item from an array list by selecting it from a JList and clicking "Delete".
The code I have so far,
buttondeleteContact.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (contactList.getSelectedIndex() != -1) {
people.removeElementAt(contactList.getSelectedIndex());
People.remove(contactList.getSelectedIndex());
System.out.println(People);
}
});
I know some things are named poorly, but people (lower case p) is the name of my DefaultListModel and People (capital P) is the name of my ArrayList. Basically, I just want to delete a block of 4 lines from an array. So, the position in the array, and the 3 after it.
While List and ArrayList don't have a direct (and accessible) removeRange() method, the need for such a method is removed by providing the subList() method.
subList() provides a view into a part of the original List. The important part to notice is that modifying the returned List will also modify the original List. So to remove the elements with the indices index to index+3, you could do this:
myList.subList(index, index+4).clear();
Note that the second argument of subList() is exclusive, so this subList() call will return a List with a size of 4.
This is an odd requirement. Deleting 3 items after it? How are they related to each other? They must be somehow related to each other. It sounds like that you have a contact list which looks like this:
List<String> contacts = new ArrayList<String>();
contacts.add("John Doe");
contacts.add("Main street 1"); // His street.
contacts.add("New York"); // His city.
contacts.add("555 123 456 789"); // His phone.
// etc..
Is this true? Then you should really consider grouping the related elements into another real-world representing object. You could create a Javabean class Contact which look like this:
public class Contact {
private String name;
private String street;
private String city; // You could consider another Address class for street and city as well.
private String phone;
// Add/generate getters and setters.
public Contact() {
// Keep default constructor alive.
}
public Contact(String name, String street, String city, String phone) {
this.name = name;
this.street = street;
this.city = city;
this.phone = phone;
}
}
This way you just end up with
List<Contact> contacts = new ArrayList<Contact>();
contacts.add(new Contact("John Doe", "Main Street 1", "New York", "555 123 456 789"));
// etc..
so that you can just remove a single real Contact by index.
You could even make it a property of People:
public class People {
private List<Contact> contacts;
// +getter +setter
}
Try to think OO.
Joachim's answer gives a good way of removing directly from an ArrayList, but I suspect you really want to remove the range directly from the model. DefaultListModel has a removeRange method:
int index = contactList.getSelectedIndex();
people.removeRange(index, index + 4);
I would expect that to have the right behaviour, removing the items from the underlying list as well. Assuming that's the case, that would be the best way of doing it I suspect. Then again, I don't know Swing very well :)
Try,
people.subList(index, index+4).clear()

Categories

Resources