I have an Arraylist inside method:
Activity{
public boolean onOptionsItemSelected(MenuItem item) {
ArrayList<Drink> mDrinkList = new ArrayList<>();
mDrinkList.add (new Drink("water", 100));
}
}
Question is: how to save items that was added to mDrinkList during previous usages of method? This method creates new ArrayList each time, so it always contains one last added item.
You need to declare mDrinkList variable outside of the method if you want its values to persist. so ArrayList<Drink> mDrinkList = new ArrayList<>(); needs to be given outside of the onOptionsItemSelected method.
you can learn more about scope of variables and declarations from here :
https://www.geeksforgeeks.org/global-local-variables-python/
Hope this helps.
Related
I am trying to move selected items from one list to another.
This code doesn't work because "itemsToMove" is a reference type and is not holding the value but instead a reference to that list.
so when i change the list i get an enumerable exception.
Dim itemsToMove = FullList.SelectedItems()
For Each item As Object In itemsToMove
GroupList.Items.Add(item)
FullList.Items.Remove(item)
Next
Is there a way to tell "itemsTomove" to take the Value of FullList.SelectedItems() instead of a reference to the memory? basically clone that list?
i did some research and i found some terms such as Boxing and Un-boxing but i do not really know if that is relevant.
If i cannot do that, does that mean This is the only (cleanest) way to do what i want?
Dim itemsToMove As Collection = New Collection()
For Each i As Object In FullList.SelectedItems()
itemsToMove.Add(i)
Next
For Each item As Object In itemsToMove
GroupList.Items.Add(item)
FullList.Items.Remove(item)
Next
If you want a copy of a reference type then it is up to you to create, yes. In this particular case, you wouldn't do it like you showed though. You can just do this:
For Each selectedItem In FullList.SelectedItems.Cast(Of Object)().ToArray()
FullList.Items.Remove(selectedItem)
GroupList.Items.Add(selectedItem)
Next
The ToArray method is quick way to create an array from an IEnumerable(Of T) and Cast(Of T) creates an IEnumerable(Of T) from an IEnumerable. In this case, as both the source and the target don't care about the specific type, you can just use Object.
I think you can use AddRange and Clear methods
This exemple below is in c#
https://dotnetfiddle.net/USSfte
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class Program
{
private static List<String> _data = new List<String>();
private static void GenerateFakeData(){
_data.AddRange(Enumerable.Range(1,100).Select((e) => String.Format("fake_{0}",e)));
}
public static void Main()
{
GenerateFakeData();
List<string> GroupList= new List<string>();
Console.WriteLine("Before\t\tGroupList.Count:{0}\t_data.Count:{1}",GroupList.Count(),_data.Count());
GroupList = new List<String>();
var FullList = SelectedItems();
/*AddRange*/
GroupList.AddRange(FullList);
/*Clear*/
FullList.Clear();
Console.WriteLine("After\t\tGroupList.Count:{0}\t_data.Count:{1}",GroupList.Count(),_data.Count());
}
public static IList<String> SelectedItems(){
return _data;
}
}
I am doing an assignment where for one of the methods, I want to create a new arraylist everytime the method is called.
Here is my method
`public boolean addMember(java.lang.String id)
{
boolean answer=true;
if(palBookMembers.size()==maxSize) {
answer=false;
}
else {
palBookMembers.add(id);
members++;
ArrayList<String> id = new ArrayList<String>();
answer=true;
}
return answer;
}
I am getting an error when I try to make an ArrayList that has the same name as the java.lang.String id variable. But, everytime this method is called I want to make an ArrayList that has a name that is unique to the id so I can use it later. For example, if the id was "Steve" I would be okay with the arrayList being called "steveId", but I just don't know how to name the arrayList this way. I tried doing
ArrayList id + "Id" = new ArrayList();
to make a name like that, but it still said the variable id was already being used. So basically, how can I name an arrayList based on the inputted id that would be unique every time the addMember method is called.
Maintain a Map keyed by id and put the new list into the map with a key of id.
In your code, the line "ArrayList id = new ArrayList();" is useless.
What are you trying to do?
I am a semi-beginner Java programmer, learning Java FX from a variety of sources. In my program, I would like to create a ComboBox, and populate the choices with the toString() output of a series of objects from an ArrayList. Here, pizza toppings are defined as an object. They are created and stored in a PizzaMgr object, basically a glorified wrapper for an ArrayList:
public class Topping{
private String name;
public Topping(String a){
this.name=a;
}
public String toString(){
return this.name;
}
}
//=================================================
import java.util.ArrayList;
public class PizzaMgr{
private ArrayList<Topping> OrderedToppings;
public PizzaMgr(){
OrderedToppings = new ArrayList<Topping>();
OrderedToppings.add(new Topping("Pepperoni"));
OrderedToppings.add(new Topping("Mushrooms"));
OrderedToppings.add(new Topping("Onions"));
}
public ArrayList<Topping> getList(){
return OrderedToppings;
}
}
So far, so good. But the hitch I hit is when I want a ComboBox to list all of those items in the PizzaMgr's ArrayList. Ideally, I'd like to use this ComboBox constructor:
ComboBox<T>(ObservableList<T> items)
The problem? How to extract all the ArrayList items into an Observable List? I've been reading up on Arraylists, Observable Lists, interfaces in general, but I can't figure out how to get this to work. I've read that an ArrayList is a Collection, and Observable List can be an interface to a Collection, so I thought I was home free. However, when I try to implement the ComboBox constructor:
import javafx.scene.control.*;
public class Menu{
public static void main(String[] args){
PizzaMgr m = new PizzaMgr();
ComboBox<Topping> topMenu = new ComboBox<Topping>(m.getList());
}
}
I get the compiler error:
Menu.java:18: error: incompatible types: ArrayList<Topping> cannot be converted to ObservableList<Topping>
ComboBox<Topping> topMenu = new ComboBox<Topping>(m.getList());
^
So obviously my ArrayList isn't seen as an Observable List.
What stumps me is: How can I present my ArrayList to the ComboBox constructor, making it seem like an Observable List? Is it a syntax slight-of-hand? Or do I have to convert the ArrayList into another data structure in advance?
Many thanks,
-RAO
ObservableList is a sub interface (specialized version of) List. (ObservableList adds functionality for observing changes to the list.) ArrayList is a particular implementation of List, but is not an implementation of ObservableList. Hence you can pass an ArrayList anywhere a List is expected, but you cannot pass an ArrayList if an ObservableList is expected.
As something of an aside, note it's not really recommended to expose the implementation type, but you should really just expose the interface type:
import java.util.List;
import java.util.ArrayList;
public class PizzaMgr{
private List<Topping> orderedToppings;
public PizzaMgr(){
orderedToppings = new ArrayList<Topping>();
orderedToppings.add(new Topping("Pepperoni"));
orderedToppings.add(new Topping("Mushrooms"));
orderedToppings.add(new Topping("Onions"));
}
public List<Topping> getList(){
return orderedToppings;
}
}
To create an ObservableList from a regular List, you can use
ComboBox<Topping> topMenu
= new ComboBox<Topping>(FXCollections.observableList(m.getList()));
which creates a new ObservableList that "wraps" the array list you provide. I.e. calling get(index) or add(item) on the observable list simply delegates to the list you provide.
You could also do
ComboBox<Topping> topMenu
= new ComboBox<Topping>(FXCollections.observableArrayList(m.getList()));
which would create a new observable list and copy all the elements from the list you provide into it. So subsequently manipulating one list would not change the other.
To create an observableList you need to, first of all, have a predefined list eg an arrayList. Pass the list to an instance of observableList as below...
//Assuming you had this for a list
List<String> list = new ArrayList<String>();
//Pass it over in this manner
ObservableList<String> observableList = FXCollections.observableList(list);
//Then add a listener
observableList.addListener (new ListChangeListener() {
//override the method here
}
Hope it will help...
ArrayList<Site> sites = new ArrayList < Site > ();
sites.add(new Site("Google", "http://www.google.com"));
ObservableList<Site> siteList = FXCollections.observableArrayList(sites);
final ComboBox comboBox = new ComboBox(siteList);
Button btn = new Button();
btn.setText("Read comboBox");
btn.setOnAction(new EventHandler < ActionEvent > () {
#Override
public void handle(ActionEvent event) {
label.setText("selected: " + comboBox.getValue());
Site site = (Site) comboBox.getSelectionModel().getSelectedItem();
System.out.println(site.name);
}
});
I want to track a list of root objects which are not contained by any element. I want the following pseudo code to work:
using (session1 = [...]) {
IList<FavoriteItem>list = session1.Linq<FavoriteItem>().ToList();
}
list.Add(item1);
list.Add(item2);
list.Remove(item3);
list.Remove(item4);
var item5 = list.First(i => i.Name = "Foo");
item5.Name = "Bar";
using (session2 = [...]) {
session2.Save(list);
}
This should automatically insert item1 and item2, delete item3 and item3 and update item5 (i.e. I don't want to call sesssion.SaveOrUpdate() for all items separately.
Is it possible to define a pseudo entity that is not associated with a table? For example I want to define the class Favorites and map 2 collection properties of it and than I want to write code like this:
using (session1 = [...]) {
var favs = session1.Linq<Favorites>();
}
favs.FavoriteColors.Add(new FavoriteColor(...));
favs.FavoriteMovies.Add(new FavoriteMovie(...));
using (session2 = [...]) {
session.SaveOrUpdate(favs);
}
FavoriteColors and FavoriteMovies are the only properties of the Favorites class and are of type IList and IList. I do only want to persist the these two collection properties but not the Favorites class.
Actually I want a IPersistentCollection object that tracks adds and removes that belongs to no parent entity and stands for itself (the same stuff that happens to collection properties of entities, only in my case I have no parent entity). This works perfectly well if the collections belong to an entity in which case I can add and remove items between two sessions.
Any help is much appreciated.
A simpler solution than a pseudo entity would be to wrap the list in an object that manages the things you want.
public class FavoriteList : IEnumerable
{
private List<FavoriteItem> list;
private ISession session;
public FavoriteList(ISession session)
{
list = session.Linq<FavoriteItem>().ToList();
this.session = session;
}
public void Add(FavoriteItem item)
{
session.SaveOrUpdate(item);
list.Add(item);
}
public void Remove(FavoriteItem item)
{
session.Delete(item); //or something like that
list.Remove(item);
}
public IEnumerator GetEnumerator()
{
return (list as IEnumerable).GetEnumerator();
}
}
I still have not found a real solution to this problem. My work around so far is that I have added the collection as a child collection property to another entity from which only one instance exists so far. But this solution breaks if there will be more instances of this entity and it has the disadvantage that the version of it is incremented every time a item is added or removed.
The other work around would have been to create a pseudo entity with no properties/columns (except an ID).
The third alternative I could think of is recreating the whole collection every time which is quite slow and does not work if other entities are referencing one of the items.
The last alternative would be to reimplement the dirty checking functionality myself but this would add some complexity and code duplication.
If somebody knows better alternatives I would be glad for any comments.
Without using DynaForm and it's kin.
I would like to use a POJO data transfer object, e.g., Person:
public class Person {
private Long id;
private String firstName;
private String lastName;
// ... getters / setters for the fields
}
In the struts live action form we would have:
public class PersonUpdateForm extends SLActionForm {
String organization;
Person[] persons; // all the people will be changed to this organization; they're names and so forth can be updated at the same time (stupid, but a client might desire this)
// getters / setters + index setters / getters for persons
}
What would the corresponding html:text tags look like in the JSP to allow this? If I switch to a List persons field and use a lazy-loading list (in commons-collections) how would that change thinsg?
There seems to be no good way to do this in struts-1.2(.9?)
All help is greatly appreciated!!! If you need more context let me know and I can provide some.
Okay, I believe I've figured it out! The trick is to have your indexed getter create an element each time the getPersons() method is called by the populate method of BeanUtils. The code is completed yet, but I got a positive looking result. It's 3:30 and I've been stuck on this a while. Nobody seemded to know the answer, which makes me want to smack them in the head with a trout. As for my own ignorance ... I only have them to blame!
public List<Person> getPersons() {
persons.add(new Person()); // BeanUtils needs to know the list is large enough
return persons;
}
Add your indexed getters and setters too, of course.
I remember how I actually did this. You must pre-initialize the persons List above to the maximum size you expect to transfer. This is because the List is first converted to an array, the properties then set on each element of the array, and finally the List set back using setPersons(...). Therefore, using a lazy-loading List implementation or similar approach (such as that show above) will NOT work with struts live. Here's what you need to do in more detail:
private List<Person> persons = new ArrayList<Person>(MAX_PEOPLE);
public MyConstructor() { for(int i = 0; i < MAX_PEOPLE; i++) persons.add(new Person()); }
public List<Person> getPeopleSubmitted() {
List<Person> copy = new ArrayList<Person>();
for(Person p : persons) {
if(p.getId() != null) copy.add(p);
// id will be set for the submitted elements;
// the others will have a null id
}
return copy; // only the submitted persons returned - not the blank templates
}
That's basically what you have to do! But the real question is - who's using struts live anymore?!