Search Results

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

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

  • Why fill() and copy() of Collections in java is implemented this way

    - by Priyank Doshi
    According to javadoc... Collections.fill() is written as below : public static <T> void fill(List<? super T> list, T obj) { int size = list.size(); if (size < FILL_THRESHOLD || list instanceof RandomAccess) { for (int i=0; i<size; i++) list.set(i, obj); } else { ListIterator<? super T> itr = list.listIterator(); for (int i=0; i<size; i++) { itr.next(); itr.set(obj); } } } Its easy to understand why they didn't use listIterator for if (size < FILL_THRESHOLD || list instanceof RandomAccess) condition as of RandomAccess. But whats the use of size < FILL_THRESHOLD in above? I mean is there any significant performance benefit over using iterator for size>=FILL_THRESHOLD and not for size < FILL_THRESHOLD ? I see the same approach for Collections.copy() also : public static <T> void copy(List<? super T> dest, List<? extends T> src) { int srcSize = src.size(); if (srcSize > dest.size()) throw new IndexOutOfBoundsException("Source does not fit in dest"); if (srcSize < COPY_THRESHOLD || (src instanceof RandomAccess && dest instanceof RandomAccess)) { for (int i=0; i<srcSize; i++) dest.set(i, src.get(i)); } else { ListIterator<? super T> di=dest.listIterator(); ListIterator<? extends T> si=src.listIterator(); for (int i=0; i<srcSize; i++) { di.next(); di.set(si.next()); } } } FYI: private static final int FILL_THRESHOLD = 25; private static final int COPY_THRESHOLD = 10;

    Read the article

  • Memory allocation for collections in .NET

    - by Yogendra
    This might be a dupe. I did not find enough information on this. I was discussing memory allocation for collections in .Net. Where is the memory for elements allocated in a collection? List<int> myList = new List<int>(); The variable myList is allocated on stack and it references the List object created on heap. The question is when int elements are added to the myList, where would they be created ? Can anyone point the right direction?

    Read the article

  • Rewrite arrays using collections

    - by owca
    I have a task, which I was able to do with the use of simplest methods - arrays. Now I'd like to go further and redo it using some more complicated java features like collections, but I've never used anything more complicated than 2d matrix. What should I look at and how to start with it. Should Tower become a Collection ? And here's the task : We have two classes - Tower and Block. Towers are built from Blocks. Ande here's sample code for testing: Block k1=new Block("yellow",1,5,4); Block k2=new Block("blue",2,2,6); Block k3=new Block("green",3,4,2); Block k4=new Block("yellow",1,5,4); Tower tower=new Tower(); tower.add(k1,k2,k3); "Added 3 blocks." System.out.println(tower); "block: green, base: 4cm x 3cm, thicknes: 2 cm block: blue, base: 6cm x 2cm, thicknes: 2 cm block: yellow, base: 5cm x 4cm, thicknes: 1 cm" tower.add(k2); "Tower already contains this block." tower.add(k4); "Added 1 block." System.out.println(tower); "block: green, base: 4cm x 3cm, thicknes: 2 cm block: blue, base: 6cm x 2cm, thicknes: 2 cm block: yellow, base: 5cm x 4cm, thicknes: 1 cm block: yellow, base: 5cm x 4cm, thicknes: 1 cm" tower.delete(k1); "Deleted 1 block" tower.delete(k1); "Block not in tower" System.out.println(tower); "block: blue, base: 6cm x 2cm, thicknes: 2 cm block: yellow, base: 5cm x 4cm, thicknes: 1 cm block: yellow, base: 5cm x 4cm, thicknes: 1 cm" Let's say I will treat Tower as a collection of blocks. How to perform search for specific block among whole collection ? Or should I use other interface ?

    Read the article

  • Database access through collections

    - by Mike
    Hi All, I have an 3 tiered application where I need to get database results and populated the UI. I have a MessagesCollection class that deals with messages. I load my user from the database. On the instantiation of a user (ie. new User()), a MessageCollection Messages = new MessageCollection(this) is performed. Message collection accepts a user as a parameter. User user = user.LoadUser("bob"); I want to get the messages for Bob. user.Messages.GetUnreadMessages(); GetUnreadMessages calls my Business Data provider which in turn calls the data access layer. The Business data provider returns List. My question is - I am not sure what the best practice is here - If I have a collection of messages in an array inside the MessagesCollection class, I could implement ICollection to provide GetEnumerator() and ability to traverse the messages. But what happens if the messages change and the the user has old messages loaded? What about big message collections? What if my user had 10,000 unread messages? I don't think accessing the database and returning 10,000 Message objects would be efficient.

    Read the article

  • Manipulating collections & the ViewModel pattern

    - by Kragen
    I'm relatively new to WPF, and I'm having trouble with what I'm fairly certain is a relatively simple problem. I have my underlying data object, a Person: class Person { public string Surname {get; set; } public string Firstname {get; set; } public List<Address> Addresses {get; } } And I wish to display and edit this object in my WPF app. To this end I've created a ViewModel that I bind to in my xaml: class PersonViewModel { public string Fullname {get; } public ObservableCollection<AddressViewModel> Addresses {get; } } This is fine, except when it comes to manipulating my Address collection, where I can't work out what I should be doing: Should I add methods AddAddress, RemoveAddress etc... to my PersonViewModel class for manipulating my collection with instances of AddressViewModel Should I just add instances of AddressViewModel to my Addresses observable collection Both of the above seem a bit messy - is there a better way of dealing with collections?

    Read the article

  • Minimal framework in Scala for collections with inheriting return type

    - by Rex Kerr
    Suppose one wants to build a novel generic class, Novel[A]. This class will contain lots of useful methods--perhaps it is a type of collection--and therefore you want to subclass it. But you want the methods to return the type of the subclass, not the original type. In Scala 2.8, what is the minimal amount of work one has to do so that methods of that class will return the relevant subclass, not the original? For example, class Novel[A] /* What goes here? */ { /* Must you have stuff here? */ def reverse/* What goes here instead of :Novel[A]? */ = //... def revrev/*?*/ = reverse.reverse } class ShortStory[A] extends Novel[A] /* What goes here? */ { override def reverse: /*?*/ = //... } val ss = new ShortStory[String] val ss2 = ss.revrev // Type had better be ShortStory[String], not Novel[String] Does this minimal amount change if you want Novel to be covariant? (The 2.8 collections do this among other things, but they also play with return types in more fancy (and useful) ways--the question is how little framework one can get away with if one only wants this subtypes-always-return-subtypes feature.)

    Read the article

  • Intersection() and Except() is too slow with large collections of custom objects

    - by Theo
    I am importing data from another database. My process is importing data from a remote DB into a List<DataModel> named remoteData and also importing data from the local DB into a List<DataModel> named localData. I am then using LINQ to create a list of records that are different so that I can update the local DB to match the data pulled from remote DB. Like this: var outdatedData = this.localData.Intersect(this.remoteData, new OutdatedDataComparer()).ToList(); I am then using LINQ to create a list of records that no longer exist in remoteData, but do exist in localData, so that I delete them from local database. Like this: var oldData = this.localData.Except(this.remoteData, new MatchingDataComparer()).ToList(); I am then using LINQ to do the opposite of the above to add the new data to the local database. Like this: var newData = this.remoteData.Except(this.localData, new MatchingDataComparer()).ToList(); Each collection imports about 70k records, and each of the 3 LINQ operation take between 5 - 10 minutes to complete. How can I make this faster? Here is the object the collections are using: internal class DataModel { public string Key1{ get; set; } public string Key2{ get; set; } public string Value1{ get; set; } public string Value2{ get; set; } public byte? Value3{ get; set; } } The comparer used to check for outdated records: class OutdatedDataComparer : IEqualityComparer<DataModel> { public bool Equals(DataModel x, DataModel y) { var e = string.Equals(x.Key1, y.Key1) && string.Equals(x.Key2, y.Key2) && ( !string.Equals(x.Value1, y.Value1) || !string.Equals(x.Value2, y.Value2) || x.Value3 != y.Value3 ); return e; } public int GetHashCode(DataModel obj) { return 0; } } The comparer used to find old and new records: internal class MatchingDataComparer : IEqualityComparer<DataModel> { public bool Equals(DataModel x, DataModel y) { return string.Equals(x.Key1, y.Key1) && string.Equals(x.Key2, y.Key2); } public int GetHashCode(DataModel obj) { return 0; } }

    Read the article

  • NullPointerException, Collections not storing data?

    - by Elliott
    Hi there, I posted this question earlier but not with the code in its entirety. The coe below also calls to other classes Background and Hydro which I have included at the bottom. I have a Nullpointerexception at the line indicate by asterisks. Which would suggest to me that the Collections are not storing data properly. Although when I check their size they seem correct. Thanks in advance. PS: If anyone would like to give me advice on how best to format my code to make it readable, it would be appreciated. Elliott package exam0607; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.Collection; import java.util.Scanner; import java.util.Vector; import exam0607.Hydro; import exam0607.Background;// this may not be necessary???? FIND OUT public class HydroAnalysis { public static void main(String[] args) { Collection hydroList = null; Collection backList = null; try{hydroList = readHydro("http://www.hep.ucl.ac.uk/undergrad/3459/exam_data/2006-07/final/hd_data.dat");} catch (IOException e){ e.getMessage();} try{backList = readBackground("http://www.hep.ucl.ac.uk/undergrad/3459/exam_data/2006-07/final/hd_bgd.dat"); //System.out.println(backList.size()); } catch (IOException e){ e.getMessage();} for(int i =0; i <=14; i++ ){ String nameroot = "HJK"; String middle = Integer.toString(i); String hydroName = nameroot + middle + "X"; System.out.println(hydroName); ALGO_1(hydroName, backList, hydroList); } } public static Collection readHydro(String url) throws IOException { URL u = new URL(url); InputStream is = u.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader b = new BufferedReader(isr); String line =""; Collection data = new Vector(); while((line = b.readLine())!= null){ Scanner s = new Scanner(line); String name = s.next(); System.out.println(name); double starttime = Double.parseDouble(s.next()); System.out.println(+starttime); double increment = Double.parseDouble(s.next()); System.out.println(+increment); double p = 0; double nterms = 0; while(s.hasNextDouble()){ p = Double.parseDouble(s.next()); System.out.println(+p); nterms++; System.out.println(+nterms); } Hydro SAMP = new Hydro(name, starttime, increment, p); data.add(SAMP); } return data; } public static Collection readBackground(String url) throws IOException { URL u = new URL(url); InputStream is = u.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader b = new BufferedReader(isr); String line =""; Vector data = new Vector(); while((line = b.readLine())!= null){ Scanner s = new Scanner(line); String name = s.next(); //System.out.println(name); double starttime = Double.parseDouble(s.next()); //System.out.println(starttime); double increment = Double.parseDouble(s.next()); //System.out.println(increment); double sum = 0; double p = 0; double nterms = 0; while((s.hasNextDouble())){ p = Double.parseDouble(s.next()); //System.out.println(p); nterms++; sum += p; } double pbmean = sum/nterms; Background SAMP = new Background(name, starttime, increment, pbmean); //System.out.println(SAMP); data.add(SAMP); } return data; } public static void ALGO_1(String hydroName, Collection backgs, Collection hydros){ //double aMin = Double.POSITIVE_INFINITY; //double sum = 0; double intensity = 0; double numberPN_SIG = 0; double POSITIVE_PN_SIG =0; //int numberOfRays = 0; for(Hydro hd: hydros){ System.out.println(hd.H_NAME); for(Background back : backgs){ System.out.println(back.H_NAME); if(back.H_NAME.equals(hydroName)){//ERROR HERE double PN_SIG = Math.max(0.0, hd.PN - back.PBMEAN); numberPN_SIG ++; if(PN_SIG 0){ intensity += PN_SIG; POSITIVE_PN_SIG ++; } } } double positive_fraction = POSITIVE_PN_SIG/numberPN_SIG; if(positive_fraction < 0.5){ System.out.println( hydroName + "is faulty" ); } else{System.out.println(hydroName + "is not faulty");} System.out.println(hydroName + "has instensity" + intensity); } } } THE BACKGROUND CLASS package exam0607; public class Background { String H_NAME; double T_START; double DT; double PBMEAN; public Background(String name, double starttime, double increment, double pbmean) { name = H_NAME; starttime = T_START; increment = DT; pbmean = PBMEAN; }} AND THE HYDRO CLASS public class Hydro { String H_NAME; double T_START; double DT; double PN; public double n; public Hydro(String name, double starttime, double increment, double p) { name = H_NAME; starttime = T_START; increment = DT; p = PN; } }

    Read the article

  • ReadOnlyCollection or IEnumerable for exposing member collections?

    - by Erik Öjebo
    Is there any reason to expose an internal collection as a ReadOnlyCollection rather than an IEnumerable if the calling code only iterates over the collection? class Bar { private ICollection<Foo> foos; // Which one is to be preferred? public IEnumerable<Foo> Foos { ... } public ReadOnlyCollection<Foo> Foos { ... } } // Calling code: foreach (var f in bar.Foos) DoSomething(f); As I see it IEnumerable is a subset of the interface of ReadOnlyCollection and it does not allow the user to modify the collection. So if the IEnumberable interface is enough then that is the one to use. Is that a proper way of reasoning about it or am I missing something? Thanks /Erik

    Read the article

  • How to load entities into private collections using the entity framework

    - by Anton P
    I have a POCO domain model which is wired up to the entity framework using the new ObjectContext class. public class Product { private ICollection<Photo> _photos; public Product() { _photos = new Collection<Photo>(); } public int Id { get; set; } public string Name { get; set; } public virtual IEnumerable<Photo> Photos { get { return _photos; } } public void AddPhoto(Photo photo) { //Some biz logic //... _photos.Add(photo); } } In the above example i have set the Photos collection type to IEnumerable as this will make it read only. The only way to add/remove photos is through the public methods. The problem with this is that the Entity Framework cannot load the Photo entities into the IEnumerable collection as it's not of type ICollection. By changing the type to ICollection will allow callers to call the Add mentod on the collection itself which is not good. What are my options? Edit: I could refactor the code so it does not expose a public property for Photos: public class Product { public Product() { Photos = new Collection<Photo>(); } public int Id { get; set; } public string Name { get; set; } private Collection<Photo> Photos {get; set; } public IEnumerable<Photo> GetPhotos() { return Photos; } public void AddPhoto(Photo photo) { //Some biz logic //... Photos.Add(photo); } } And use the GetPhotos() to return the collection. The other problem with the approach is that I will loose the change tracking abilities as I cannot mark the collection as Virtual - It is not possible to mark a property as private virtual. In NHibernate I believe it's possible to map the proxy class to the private collection via configuration. I hope that this will become a feature of EF4. Currently i don't like the inability to have any control over the collection!

    Read the article

  • Generics & Collections!

    - by RayAllen
    I had a doubt. Why,generics (in java or any other lang), works with the objects and not with primitive types ? For e.g Gen< Integer inum=new Gen< Integer(100); works fine , but Gen< int inums=new Gen< int(100); is not allowed. Thanks !

    Read the article

  • Nhibernate , collections and compositeid

    - by Ciaran
    Hi, banging my head here and thought that some one out there might be able to help. Have Tables below. Bucket( bucketId smallint (PK) name varchar(50) ) BucketUser( UserId varchar(10) (PK) bucketId smallint (PK) ) The composite key is not the problem thats ok I know how to get around this but I want my bucket class to contanin a IList of BucketUser. I read the online reference and thought that I had cracked it but havent. The two mappings are below -- bucket -- <id name="BucketId" column="BucketId" type="Int16" unsaved-value="0"> <generator class="native"/> </id> <property column="BucketName" type="String" name="BucketName"/> <bag name="Users" table="BucketUser" inverse="true" generic="true" lazy="true"> <key> <column name="BucketId" sql-type="smallint"/> <column name="UserId" sql-type="varchar"/> </key> <one-to-many class="Bucket,Impact.Dice.Core" not-found="ignore"/> </bag> -- bucketUser --

    Read the article

  • Java Collections and Garbage Collector

    - by Anth0
    A little question regarding performance in a Java web app. Let's assume I have a List<Rubrique> listRubriques with ten Rubrique objects. A Rubrique contains one list of products (List<product> listProducts) and one list of clients (List<Client> listClients). What exactly happens in memory if I do this: listRubriques.clear(); listRubriques = null; My point of view would be that, since listRubriques is empty, all my objects previously referenced by this list (including listProducts and listClients) will be garbage collected pretty soon. But since Collection in Java are a little bit tricky and since I have quite performance issues with my app i'm asking the question :) edit : let's assume now that my Client object contains a List<Client>. Therefore, I have kind of a circular reference between my objects. What would happen then if my listRubrique is set to null? This time, my point of view would be that my Client objects will become "unreachable" and might create a memory leak?

    Read the article

  • Autowiring collections with IoC

    - by Marcus
    Hi, Anyone know if there exists any IoC container that can handle this: Given: ISomeInterfce<T> where T : Entity Impl1 : ISomeInterfce<Entity1> Impl2 : ISomeInterfce<Entity1> Impl3 : ISomeInterfce<Entity2> Impl4 : ISomeInterfce<Entity2> I want to be able to auto wire my system and be able to resolve like this IoC.ResolveAll(typeof(ISomeInterfce<Entity1>)) and get a collection back of all implementations of ISomeInterfce<Entity1>

    Read the article

  • Generics and collections ... struggling with an implementation

    - by mattruma
    I am trying to figure out a way to leverage generics so I can make the property Value be an actual type that initialized (not sure if this is the correct way of saying it) when my collection class is created. I would like to have the syntax be something like: var list = new ListItemCollection<Guid>(parameters would go here); I have the following class: [Serializable] public class ListItem { public object Value { get; set; } public string Text { get; set; } public object DataContext { get; set; } public Nullable<bool> Checked { get; set; } public ListItem() { this.Checked = false; } } I have the following collection: [Serializable] public class ListItemCollection : List<ListItem> { public ListItem this[object value] { get { foreach (var child in this) { if (child.Value.Equals(value)) return child; } return null; } } public bool Contains(object value) { foreach (var child in this) { if (child.Value.Equals(value)) return true; } return false; } public void Add(object value, string text) { this.Add(value, text, null); } public void Add(object value, string text, object dataContext) { var child = new ListItem(); child.Value = value; child.Text = text; child.DataContext = dataContext; this.Add(child); } public ListItemCollection() { } public ListItemCollection(IEnumerable items, string displayMember, string valueMember, bool showEmptyItem, string emptyItemText, object emptyItemValue) { if (showEmptyItem) { this.Add(emptyItemValue, emptyItemText); } foreach (object item in items) { object text = null; object value = null; text = item.GetType().GetProperty(displayMember).GetValue(item, null); value = item.GetType().GetProperty(valueMember).GetValue(item, null); // Add the item this.Add(value, text.ToString(), item); } } }

    Read the article

  • Better type safety in Java collections

    - by Paul Tomblin
    In my java coding, I often end up with several Map<String,Map<String,foo>> or Map<String,List<String>> and then I have trouble remembering which String is which key. I comment the declaration with //Map<capabiltyId,Map<groupId,foo>> or //Map<groupId,List<capabilityId>, but it's not the greatest solution. If String wasn't final, I would make new classes CapabilityId extends String and GroupId extends String, but I can't. Is there a better way to keep track of which thing is the key and maybe have the compiler enforce it?

    Read the article

  • Subsonic, child records, and collections

    - by Dane
    Hi, I've been working with subsonic for a few weeks now, and it is working really well. However, I've just run into an issue with child objects with additional partial properties. Some of it is probably me just not understanding the .Net object lifecycle. I have an object - search. This has a few properties like permissions and stuff, and it links to a child table called search_options. In my Asp.Net app, it loops through these search options and creates controls. Then on postback, it grabs the values and assigns it back to a "value" property on the search_option. This value property is a simple string that's defined in a partial class. I then want to create a method on the search object, called PerformSearch. This then loops through the child search_options, and performs a custom query based on the "value" property. However, even though I assign the "value" property to the child search_option, when I access it later via the search.search_options collection, it is null. I'm guessing that maybe because it's accessing it in two different places, it performs another lazy load from the DB and the value is lost? Is there a way to tell the class that it's already loaded or something? or a way to access it so it's not reloaded from the DB? Code is below (shitty pseudocode, not full version) : ASP.Net page, loading back the values from postback : dim obj_search as search = new subsonic.query.select().......' retrieves the search object for each opt as search_option in obj_search.search_options opt.Value = Ctype(FindControl("search_option_" + opt.search_option_id),Textbox).Text debug.print(opt.Value) ' value is correct next for each opt as search_option in obj_search.search_options debug.print(opt.Value) 'this is nothing next Now, the partial class : public partial class search_option private m_value as string public property Value() as string get return m_value end get set( byval value as string) m_value = value end set end property end class

    Read the article

  • Searching through Collections in Java

    - by Click Upvote
    I have a java properties file containing a key/value pair of country names and codes. I will load the contents of this file into a Collection like List or HashMap. Then, I want users to be able to search for a country, e.g if they type 'Aus' in a textbox and click submit, then I want to search through the collection I have, containing a key/value pair of country codes/names (e.g AUS=Australia), and return those countries which are found matching. Is there any more efficient way of doing this, other than looping through the elements of the collection and using charAt()?

    Read the article

  • Why does C# not implement GetHashCode for Collections?

    - by Peterdk
    I am porting something from Java to C#. In Java the hashcode of a ArrayList depends on the items in it. In C# I always get the same hashcode from a List... Why is this? For some of my objects the hashcode needs to be different because the objects in their list property make the objects non-equal. I would expect that a hashcode is always unique for the object's state and only equals another hashcode when the object is equal. Am I wrong?

    Read the article

  • customising serialisation of java collections using xstream

    - by Will Goring
    I have an object that needs to be serialised as XML, which contains the following field: List<String> tags = new List<String>(); XStream serialises it just fine (after some aliases) like this: <tags> <string>tagOne</string> <string>tagTwo</string> <string>tagThree</string> <string>tagFour</string> </tags> That's OK as far as it goes, but I'd like to be able to rename the <string> elements to, say, <tag>. I can't see an obvious way to do that from the alias documentation on the XStream site. Am I missing something obvious?

    Read the article

  • How to load entities into readonly collections using the entity framework

    - by Anton P
    I have a POCO domain model which is wired up to the entity framework using the new ObjectContext class. public class Product { private ICollection<Photo> _photos; public Product() { _photos = new Collection<Photo>(); } public int Id { get; set; } public string Name { get; set; } public virtual IEnumerable<Photo> Photos { get { return _photos; } } public void AddPhoto(Photo photo) { //Some biz logic //... _photos.Add(photo); } } In the above example i have set the Photos collection type to IEnumerable as this will make it read only. The only way to add/remove photos is through the public methods. The problem with this is that the Entity Framework cannot load the Photo entities into the IEnumerable collection as it's not of type ICollection. By changing the type to ICollection will allow callers to call the Add mentod on the collection itself which is not good. What are my options?

    Read the article

  • Java: Finding objects in collections.

    - by Jake
    This problem occurs over and over. I have some complicated object, such as a Cat, which has many properties, such as age, favorite cat food, and so forth. A bunch of Cats are stored in a Java Collection, and I need to find all the Cats that are aged 3, or those whose favorite cat food is Whiskas. Surely, I can write a custom method that finds those Cats with a specific property, but this gets cumbersome with many properties; is there some generic way of doing this?

    Read the article

  • Collections removeAll method

    - by srinannapa
    I would like to know if something like below is possible , list<**MyObject**>.**removeAll**(list<**String**>) I hope the context is understandable. The list<MyObject : is a ArrayList<MyObject The list<String : is a ArrayList<String I know this can be achieved by overriding equals method in MyObject class. I would like to know if any other choice is prsent. Thanks,Srinivas N

    Read the article

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