Search Results

Search found 2563 results on 103 pages for 'collections'.

Page 6/103 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • ArrayList in Java [on hold]

    - by JNL
    I was implementing a program to remove the duplicates from the 2 character array. I implemented these 2 solutions, Solution 1 worked fine, but Solution 2 given me UnSupportedoperationException. I am wonderring why i sthat so? The two solutions are given below; public void getDiffernce(Character[] inp1, Character[] inp2){ // Solution 1: // ********************************************************************************** List<Character> list1 = new ArrayList<Character>(Arrays.asList(inp1)); List<Character> list2 = new ArrayList<Character>(Arrays.asList(inp2)); list1.removeAll(list2); System.out.println(list1); System.out.println("*********************************************************************************"); // Solution 2: Character a[] = {'f', 'x', 'l', 'b', 'y'}; Character b[] = {'x', 'b','d'}; List<Character> al1 = new ArrayList<Character>(); List<Character> al2 = new ArrayList<Character>(); al1 = (Arrays.asList(a)); System.out.println(al1); al2 = (Arrays.asList(b)); System.out.println(al2); al1.removeAll(al2); // retainAll(al2); System.out.println(al1); }

    Read the article

  • "Collection Wrapper" pattern - is this common?

    - by Prog
    A different question of mine had to do with encapsulating member data structures inside classes. In order to understand this question better please read that question and look at the approach discussed. One of the guys who answered that question said that the approach is good, but if I understood him correctly - he said that there should be a class existing just for the purpose of wrapping the collection, instead of an ordinary class offering a number of public methods just to access the member collection. For example, instead of this: class SomeClass{ // downright exposing the concrete collection. Things[] someCollection; // other stuff omitted Thing[] getCollection(){return someCollection;} } Or this: class SomeClass{ // encapsulating the collection, but inflating the class' public interface. Thing[] someCollection; // class functionality omitted. public Thing getThing(int index){ return someCollection[index]; } public int getSize(){ return someCollection.length; } public void setThing(int index, Thing thing){ someCollection[index] = thing; } public void removeThing(int index){ someCollection[index] = null; } } We'll have this: // encapsulating the collection - in a different class, dedicated to this. class SomeClass{ CollectionWrapper someCollection; CollectionWrapper getCollection(){return someCollection;} } class CollectionWrapper{ Thing[] someCollection; public Thing getThing(int index){ return someCollection[index]; } public int getSize(){ return someCollection.length; } public void setThing(int index, Thing thing){ someCollection[index] = thing; } public void removeThing(int index){ someCollection[index] = null; } } This way, the inner data structure in SomeClass can change without affecting client code, and without forcing SomeClass to offer a lot of public methods just to access the inner collection. CollectionWrapper does this instead. E.g. if the collection changes from an array to a List, the internal implementation of CollectionWrapper changes, but client code stays the same. Also, the CollectionWrapper can hide certain things from the client code - from example, it can disallow mutation to the collection by not having the methods setThing and removeThing. This approach to decoupling client code from the concrete data structure seems IMHO pretty good. Is this approach common? What are it's downfalls? Is this used in practice?

    Read the article

  • How do I implement a collection in Scala 2.8?

    - by Simon Reinhardt
    In trying to write an API I'm struggling with Scala's collections in 2.8(.0-beta1). Basically what I need is to write something that: adds functionality to immutable sets of a certain type where all methods like filter and map return a collection of the same type without having to override everything (which is why I went for 2.8 in the first place) where all collections you gain through those methods are constructed with the same parameters the original collection had (similar to how SortedSet hands through an ordering via implicits) which is still a trait in itself, independent of any set implementations. Additionally I want to define a default implementation, for example based on a HashSet. The companion object of the trait might use this default implementation. I'm not sure yet if I need the full power of builder factories to map my collection type to other collection types. I read the paper on the redesign of the collections API but it seems like things have changed a bit since then and I'm missing some details in there. I've also digged through the collections source code but I'm not sure it's very consistent yet. Ideally what I'd like to see is either a hands-on tutorial that tells me step-by-step just the bits that I need or an extensive description of all the details so I can judge myself which bits I need. I liked the chapter on object equality in "Programming in Scala". :-) But I appreciate any pointers to documentation or examples that help me understand the new collections design better.

    Read the article

  • Google Collections sources don't compile

    - by Carl Rosenberger
    I just downloaded the Google Collections sources and imported them into a new Eclipse project with JDK 1.6. They don't compile for a couple of reasons: javax.annotation.Nullable can not be found javax.annotation.ParametersAreNonnullByDefault can not be found Cannot reduce the visibility of the inherited method #createCollection() from AbstractMultimap + 11 similar ones Name clash: The method forcePut(K, V) of type AbstractBiMap has the same erasure as forcePut(Object, Object) of type BiMap but does not override it + 2 similar ones What am I missing? I also wonder if unit tests for these collections are available to the public.

    Read the article

  • Does .NET have a built in IEnumerable for multiple collections?

    - by Bryce Wagner
    I need an easy way to iterate over multiple collections without actually merging them, and I couldn't find anything built into .NET that looks like it does that. It feels like this should be a somewhat common situation. I don't want to reinvent the wheel. Is there anything built in that does something like this: public class MultiCollectionEnumerable<T> : IEnumerable<T> { private MultiCollectionEnumerator<T> enumerator; public MultiCollectionEnumerable(params IEnumerable<T>[] collections) { enumerator = new MultiCollectionEnumerator<T>(collections); } public IEnumerator<T> GetEnumerator() { enumerator.Reset(); return enumerator; } IEnumerator IEnumerable.GetEnumerator() { enumerator.Reset(); return enumerator; } private class MultiCollectionEnumerator<T> : IEnumerator<T> { private IEnumerable<T>[] collections; private int currentIndex; private IEnumerator<T> currentEnumerator; public MultiCollectionEnumerator(IEnumerable<T>[] collections) { this.collections = collections; this.currentIndex = -1; } public T Current { get { if (currentEnumerator != null) return currentEnumerator.Current; else return default(T); } } public void Dispose() { if (currentEnumerator != null) currentEnumerator.Dispose(); } object IEnumerator.Current { get { return Current; } } public bool MoveNext() { if (currentIndex >= collections.Length) return false; if (currentIndex < 0) { currentIndex = 0; if (collections.Length > 0) currentEnumerator = collections[0].GetEnumerator(); else return false; } while (!currentEnumerator.MoveNext()) { currentEnumerator.Dispose(); currentEnumerator = null; currentIndex++; if (currentIndex >= collections.Length) return false; currentEnumerator = collections[currentIndex].GetEnumerator(); } return true; } public void Reset() { if (currentEnumerator != null) { currentEnumerator.Dispose(); currentEnumerator = null; } this.currentIndex = -1; } } }

    Read the article

  • WCF: Serializing and Deserializing generic collections

    - by Fabiano
    I have a class Team that holds a generic list: [DataContract(Name = "TeamDTO", IsReference = true)] public class Team { [DataMember] private IList<Person> members = new List<Person>(); public Team() { Init(); } private void Init() { members = new List<Person>(); } [System.Runtime.Serialization.OnDeserializing] protected void OnDeserializing(StreamingContext ctx) { Log("OnDeserializing of Team called"); Init(); if (members != null) Log(members.ToString()); } [System.Runtime.Serialization.OnSerializing] private void OnSerializing(StreamingContext ctx) { Log("OnSerializing of Team called"); if (members != null) Log(members.ToString()); } [System.Runtime.Serialization.OnDeserialized] protected void OnDeserialized(StreamingContext ctx) { Log("OnDeserialized of Team called"); if (members != null) Log(members.ToString()); } [System.Runtime.Serialization.OnSerialized] private void OnSerialized(StreamingContext ctx) { Log("OnSerialized of Team called"); Log(members.ToString()); } When I use this class in a WCF service, I get following log output OnSerializing of Team called System.Collections.Generic.List 1[Person] OnSerialized of Team called System.Collections.Generic.List 1[Person] OnDeserializing of Team called System.Collections.Generic.List 1[ENetLogic.ENetPerson.Model.FirstPartyPerson] OnDeserialized of Team called ENetLogic.ENetPerson.Model.Person[] After the deserialization members is an Array and no longer a generic list although the field type is IList< (?!) When I try to send this object back over the WCF service I get the log output OnSerializing of Team called ENetLogic.ENetPerson.Model.FirstPartyPerson[] After this my unit test crashes with a System.ExecutionEngineException, which means the WCF service is not able to serialize the array. (maybe because it expected a IList<) So, my question is: Does anybody know why the type of my IList< is an array after deserializing and why I can't serialize my Team object any longer after that? Thanks

    Read the article

  • Deserialize generic collections - coming up empty

    - by AC
    I've got a settings object for my app that has two collections in it. The collections are simple List generics that contain a collection of property bags. When I serialize it, everything is saved with no problem: XmlSerializer x = new XmlSerializer(settings.GetType()); TextWriter tw = new StreamWriter(@"c:\temp\settings.cpt"); x.Serialize(tw, settings); However when I deserialize it, everything is restored except for the two collections (verified by setting a breakpoint on the setters: XmlSerializer x = new XmlSerializer(typeof(CourseSettings)); XmlReader tr = XmlReader.Create(@"c:\temp\settings.cpt"); this.DataContext = (CourseSettings)x.Deserialize(tr); What would cause this? Everything is pretty vanilla... here's a snippet from the settings object... omitting most of it. The PresentationSourceDirectory works just fine, but the PresentationModules' setter isn't hit: private string _presentationSourceDirectory = string.Empty; public string PresentationSourceDirectory { get { return _presentationSourceDirectory; } set { if (_presentationSourceDirectory != value) { OnPropertyChanged("PresentationSourceDirectory"); _presentationSourceDirectory = value; } } } private List<Module> _presentationModules = new List<Module>(); public List<Module> PresentationModules { get { var sortedModules = from m in _presentationModules orderby m.ModuleOrder select m; return sortedModules.ToList<Module>(); } set { if (_presentationModules != value) { _presentationModules = value; OnPropertyChanged("PresentationModules"); } } }

    Read the article

  • Best practice when removing entity regarding mappedBy collections?

    - by Daniel Bleisteiner
    I'm still kind of undecided which is the best practice to handle em.remove(entity) with this entity being in several collections mapped using mappedBy in JPA. Consider an entity like a Property that references three other entities: a Descriptor, a BusinessObject and a Level entity. The mapping is defined using @ManyToOne in the Property entity and using @OneToMany(mappedBy...) in the other three objects. That inverse mapping is defined because there are some situations where I need to access those collections. Whenever I remove a Property using em.remove(prop) this element is not automatically removed from managed entities of the other three types. If I don't care about that and the following page load (webapp) doesn't reload those entities the Property is still found and some decisions might be taken that are no longer true. The inverse mappings may become quite large and though I don't want to use something like descriptor.getProperties().remove(prop) because it will load all those properties that might have been lazy loaded until then. So my currently preferred way is to refresh the entity if it is managed: if (em.contains(descriptor)) em.refresh(descriptor) - which unloads a possibly loaded collection and triggers a reload upon the next access. Is there another feasible way to handle all those mappedBy collections of already loaded entites?

    Read the article

  • Iterating Oracle collections of objects with out exploding them

    - by Scott Bailey
    I'm using Oracle object data types to represent a timespan or period. And I've got to do a bunch of operations that involve working with collections of periods. Iterating over collections in SQL is significantly faster than in PL/SQL. CREATE TYPE PERIOD AS OBJECT ( beginning DATE, ending DATE, ... some member functions...); CREATE TYPE PERIOD_TABLE AS TABLE OF PERIOD; -- sample usage SELECT <<period object>>.contains(period2) FROM TABLE(period_table1) t The problem is that the TABLE() function explodes the objects into scalar values, and I really need the objects instead. I could use the scalar values to recreate the objects but this would incur the overhead of re-instantiating the objects. And the period is designed to be subclassed so there would be additional difficulty trying to figure out what to initialize it as. Is there another way to do this that doesn't destroy my objects?

    Read the article

  • How can I modify my classes to use it's collections in WPF TreeView

    - by Victor
    Hello, i'am trying to modify my objects to make hierarchical collection model. I need help. My objects are Good and GoodCategory: public class Good { int _ID; int _GoodCategory; string _GoodtName; public int ID { get { return _ID; } } public int GoodCategory { get { return _GoodCategory; } set { _GoodCategory = value; } } public string GoodName { get { return _GoodName; } set { _GoodName = value; } } public Good(IDataRecord record) { _ID = (int)record["ID"]; _GoodtCategory = (int)record["GoodCategory"]; } } public class GoodCategory { int _ID; string _CategoryName; public int ID { get { return _ID; } } public string CategoryName { get { return _CategoryName; } set { _CategoryName = value; } } public GoodCategory(IDataRecord record) { _ID = (int)record["ID"]; _CategoryName = (string)record["CategoryName"]; } } And I have two Collections of these objects: public class GoodsList : ObservableCollection<Good> { public GoodsList() { string goodQuery = @"SELECT `ID`, `ProductCategory`, `ProductName`, `ProductFullName` FROM `products`;"; using (MySqlConnection conn = ConnectToDatabase.OpenDatabase()) { if (conn != null) { MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = productQuery; MySqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { Add(new Good(rdr)); } } } } } public class GoodCategoryList : ObservableCollection<GoodCategory> { public GoodCategoryList () { string goodQuery = @"SELECT `ID`, `CategoryName` FROM `product_categoryes`;"; using (MySqlConnection conn = ConnectToDatabase.OpenDatabase()) { if (conn != null) { MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = productQuery; MySqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { Add(new GoodCategory(rdr)); } } } } } So I have two collections which takes data from the database. But I want to use thats collections in the WPF TreeView with HierarchicalDataTemplate. I saw many post's with examples of Hierarlichal Objects, but I steel don't know how to make my objects hierarchicaly. Please help.

    Read the article

  • Proper usage of Java Weak Reference in case of nested collections

    - by Tong Wang
    I need to define a weak reference Map, whose value is a Set. I use Google collections' MapMaker, like this: Map<Class<? extends Object>, Set<Foo>> map = new MapMaker().weakKeys().weakValues().makeMap(); So, for Set<Foo>, can I use a normal HashSet? Or, do I have to create a weak HashSet, like this: Collections.newSetFromMap(new WeakHashMap<Foo, Boolean>()); And why? Another question, the key of my map is Class objects, when will a Class object become weakly reachable? In other words, what is the lifetime of a Class object? Thanks.

    Read the article

  • Java Collections.Rotate with an array doesn't work

    - by steve_72
    I have the following java code: import java.util.Arrays; import java.util.Collections; public class Test { public static void main(String[] args) { int[] test = {1,2,3,4,5}; Collections.rotate(Arrays.asList(test), -1); for(int i = 0; i < test.length; i++) { System.out.println(test[i]); } } } I want the array to be rotated, but the output I get is 1 2 3 4 5 Why is this? And is there an alternative solution?

    Read the article

  • Writing a synchronized thread-safety wrapper for NavigableMap

    - by polygenelubricants
    java.util.Collections currently provide the following utility methods for creating synchronized wrapper for various collection interfaces: synchronizedCollection(Collection<T> c) synchronizedList(List<T> list) synchronizedMap(Map<K,V> m) synchronizedSet(Set<T> s) synchronizedSortedMap(SortedMap<K,V> m) synchronizedSortedSet(SortedSet<T> s) Analogously, it also has 6 unmodifiedXXX overloads. The glaring omission here are the utility methods for NavigableMap<K,V>. It's true that it extends SortedMap, but so does SortedSet extends Set, and Set extends Collection, and Collections have dedicated utility methods for SortedSet and Set. Presumably NavigableMap is a useful abstraction, or else it wouldn't have been there in the first place, and yet there are no utility methods for it. So the questions are: Is there a specific reason why Collections doesn't provide utility methods for NavigableMap? How would you write your own synchronized wrapper for NavigableMap? Glancing at the source code for OpenJDK version of Collections.java seems to suggest that this is just a "mechanical" process Is it true that in general you can add synchronized thread-safetiness feature like this? If it's such a mechanical process, can it be automated? (Eclipse plug-in, etc) Is this code repetition necessary, or could it have been avoided by a different OOP design pattern?

    Read the article

  • which collection should I use

    - by Masna
    Hello, I have a number of custom objects of type X. X has a number of parameters and must be unique in the collection. (I created my own equals method based on the custom parameters to examine this) In each object of type x, I have a list of objects y. I want to add/remove/modify easily an object y. For example: To write the add method, it would be something like add(objTypeX, objTypeY) I would check or the collections already has a objTypeX. If so: i would add the objTypeY to the already existing objTypeX else: i would create objTypeX and add objTypeY to this object. To modify an objTypeY, it would be something like(objTypeX, objTypeY, newobjTypeY) I would get objTypeX out of the collections and modify objTypeY to newobjTypeY Which collections should I use? I tried with hashset but i can get a specific object out of the list, without run down the list till I find that object. I develop this in vb.net 3.5

    Read the article

  • Direct comparator in Java out of the box

    - by KARASZI István
    I have a method which needs a Comparator for one of its parameters. I would like to pass a Comparator which does a normal comparison and a reverse comparator which does in reverse. java.util.Collections provides a reverseOrder() this is good for the reverse comparison, but I could not find any normal Comparator. The only solution what came into my mind is Collections.reverseOrder(Collections.reverseOrder()). but I don't like it because the double method calling inside. Of course I could write a NormalComparator like this: public class NormalComparator<T extends Comparable> implements Comparator<T> { public int compare(T o1, T o2) { return o1.compareTo(o2); } } But I'm really surprised that Java doesn't have a solution for this out of the box.

    Read the article

  • is it possible to write data to a collection in wpf?

    - by randyc
    Hello. In looking through samples I have seen a number of examples where it is possible to present data within a wpf applicaiton by binding to collections. However I was wondering is it possible to write to a collection from an applicaiton. Say for example i have 2 or more fields such as names and I wanted to have hte ability to add up to three names in my application ( all stored in memory). Will collections serve this purpose. In the past with asp.net I have done this by creating data tables and storing values on the fly or during the session. I am trying to learn WPF and I was wondering if collections work in the same fashion? If so could you please post an example or point me to references that show examples of this? Thank you in advance.

    Read the article

  • What are the requirements of a collection type when model binding?

    - by Richard Ev
    I have been reviewing model binding with collections, specifically going through this article http://weblogs.asp.net/nmarun/archive/2010/03/13/asp-net-mvc-2-model-binding-for-a-collection.aspx However, the model I would like to use in my code does not implement collections using generic lists. Instead it uses its own collection classes, which inherit from a custom generic collection base class, the declaration of which is public abstract class CollectionBase<T> : IEnumerable<T> The collections in my POSTed action method are all non-null, but contain no elements. Can anyone advise?

    Read the article

  • Fluent NHibernate Automap does not take into account IList<T> collections as indexed

    - by Francisco Lozano
    I am using automap to map a domain model (simplified version): public class AppUser : Entity { [Required] public virtual string NickName { get; set; } [Required] [DataType(DataType.Password)] public virtual string PassKey { get; set; } [Required] [DataType(DataType.EmailAddress)] public virtual string EmailAddress { get; set; } public virtual IList<PreferencesDescription> PreferencesDescriptions { get; set; } } public class PreferencesDescription : Entity { public virtual AppUser AppUser { get; set; } public virtual string Content{ get; set; } } The PreferencesDescriptions collection is mapped as an IList, so is an indexed collection (when I require standard unindexed collections I use ICollection). The fact is that fluent nhibernate's automap facilities map my domain model as an unindexed collection (so there's no "position" property in the DDL generated by SchemaExport). ¿How can I make it without having to override this very case - I mean, how can I make Fluent nhibernate's automap make always indexed collections for IList but not for ICollection

    Read the article

  • Render multiple control collections in ASP.NET custom control

    - by Monty
    I've build a custom WebControl, which has the following structure: <gws:ModalBox ID="ModalBox1" HeaderText="Title" runat="server"> <Contents>(controls...)</Contents> <Footer>(controls...)</Footer> </gws:ModalBox> The control contains two ControlCollection properties, 'Contents' and 'Footer'. Never tried to build a control with multiple control collections, but solved it like this (simplified): [PersistChildren(false), ParseChildren(true)] public class ModalBox : WebControl { private ControlCollection _contents; private ControlCollection _footer; public ModalBox() : base() { this._contents = base.CreateControlCollection(); this._footer = base.CreateControlCollection(); } [PersistenceMode(PersistenceMode.InnerProperty)] public ControlCollection Contents { get { return this._contents; } } [PersistenceMode(PersistenceMode.InnerProperty)] public ControlCollection Footer { get { return this._footer; } } protected override void RenderContents(HtmlTextWriter output) { // Render content controls. foreach (Control control in this.Contents) { control.RenderControl(output); } // Render footer controls. foreach (Control control in this.Footer) { control.RenderControl(output); } } } However it seems to render properly, it doesn't work anymore if I add some asp.net labels and input controls inside the property. I'll get the HttpException: Unable to find control with id 'KeywordTextBox' that is associated with the Label 'KeywordLabel'. Somewhat understandable, because the label appears before the textbox in the controlcollection. However, with default asp.net controls it does work, so why doesn't this work? What am I doing wrong? Is it even possible to have two control collections in one control? Should I render it differently? Thanks for replies.

    Read the article

  • Load collections eagerly in NHibernate using Criteria API

    - by Zuber
    I have an entity A which HasMany entities B and entities C. All entities A, B and C have some references x,y and z which should be loaded eagerly. I want to read from the database all entities A, and load the collections of B and C eagerly using criteria API. So far, I am able to fetch the references in 'A' eagerly. But when the collections are loaded, the references within them are lazily loaded. Here is how I do it AllEntities_A = _session.CreateCriteria(typeof(A)) .SetFetchMode("x", FetchMode.Eager) .SetFetchMode("y", FetchMode.Eager) .List<A>().AsQueryable(); The mapping of entity A using Fluent is as shown below. _B and _C are private ILists for B & C respectively in A. Id(c => c.SystemId); Version(c => c.Version); References(c => c.x).Cascade.All(); References(c => c.y).Cascade.All(); HasMany<B>(Reveal.Property<A>("_B")) .AsBag() .Cascade.AllDeleteOrphan() .Not.LazyLoad() .Inverse() .Cache.ReadWrite().IncludeAll(); HasMany<C>(Reveal.Property<A>("_C")) .AsBag() .Cascade.AllDeleteOrphan() .LazyLoad() .Inverse() .Cache.ReadWrite().IncludeAll(); I don't want to make changes to the mapping file, and would like to load the entire entity A eagerly. i.e. I should get a List of A's where there will be List of B's and C's whose reference properties will also be loaded eagerly

    Read the article

  • More nest Python nested dictionaries.

    - by clutch
    After reading http://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python why is it wrong to do: c = collections.defaultdict(collections.defaultdict(int)) in python? I would think this would work to produce {key:{key:1}} or am I thinking about it wrong?

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >