Search Results

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

Page 16/103 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • Convert SelectedObjectCollection to Collection of Specific Type

    - by Jonathan Wood
    I have a WinForms multiselect listbox, and each item in the listbox is of type MyClass. I am also writing a method that needs to take a parameter that is a collection of MyClass. It could be of type MyClass[], List<MyClass>, IList<MyClass>, IEnumerable<MyClass>, etc. Any of those would work fine. Somehow, I need to pass the selected items in the listbox to my method. But how would I convert SelectedObjectCollection to any of the MyClass collection types described above?

    Read the article

  • Clojure: seq (cons) vs. list (conj)

    - by dbyrne
    I know that cons returns a seq and conj returns a collection. I also know that conj "adds" the item to the optimal end of the collection, and cons always "adds" the item to the front. This example illustrates both of these points: user=> (conj [1 2 3] 4) //returns a collection [1 2 3 4] user=> (cons 4 [1 2 3]) //returns a seq (4 1 2 3) For vectors, maps, and sets these differences make sense to me. However, for lists they seem identical. user=> (conj '(3 2 1) 4) (4 3 2 1) user=> (cons 4 '(3 2 1)) (4 3 2 1) Are there any examples using lists where conj vs. cons exhibit different behaviors, or are they truly interchangeable? Phrased differently, is there an example where a list and a seq cannot be used equivalently?

    Read the article

  • Adding two Set[Any]

    - by Alex Boisvert
    Adding two Set[Int] works: Welcome to Scala version 2.8.1.final (Java HotSpot(TM) Server VM, Java 1.6.0_23). Type in expressions to have them evaluated. Type :help for more information. scala> Set(1,2,3) ++ Set(4,5,6) res0: scala.collection.immutable.Set[Int] = Set(4, 5, 6, 1, 2, 3) But adding two Set[Any] doesn't: scala> Set[Any](1,2,3) ++ Set[Any](4,5,6) <console>:6: error: ambiguous reference to overloaded definition, both method ++ in trait Addable of type (xs: scala.collection.TraversableOnce[Any])scala.collection.immutable.Set[Any] and method ++ in trait TraversableLike of type [B >: Any,That](that: scala.collection.TraversableOnce[B])(implicit bf: scala.collection.generic.CanBuildFrom[scala.collection.immutable.Set[Any],B,That])That match argument types (scala.collection.immutable.Set[Any]) Set[Any](1,2,3) ++ Set[Any](4,5,6) ^ Any suggestion to work around this error?

    Read the article

  • How to bundle extension methods requiring configuration in a library

    - by Greg
    Hi, I would like to develop a library that I can re-use to add various methods involved in navigating/searching through a graph (nodes/relationships, or if you like vertexs/edges). The generic requirements would be: There are existing classes in the main project that already implement the equivalent of the graph class (which contains the lists of nodes / relationships), node class and relationship class (which links nodes together) - the main project likely already has persistence mechanisms for the info (e.g. these classes might be built using Entity Framework for persistance) Methods would need to be added to each of these 3 classes: (a) graph class - methods like "search all nodes", (b) node class - methods such as "find all children to depth i", c) relationship class - methods like "return relationship type", "get parent node", "get child node". I assume there would be a need to inform the library with the extending methods the class names for the graph/node/relationships table (as different project might use different names). To some extent it would need to be like how a generics collection works (where you pass the classes to the collection so it knows what they are). Need to be a way to inform the library of which node property to use for equality checks perhaps (e.g. if it were a graph of webpages the equality field to use might be the URI path) I'm assuming that using abstract base classes wouldn't really work as this would tie usage down to have to use the same persistence approach, and same class names etc. Whereas really I want to be able to, for a project that has "graph-like" characteristics, the ability to add graph searching/walking methods to it.

    Read the article

  • Is there a SortedList<T> class in .net ? (not SortedList<Key,Value> which is actually a kind of Sort

    - by Brann
    I need to sort some objects according to their contents (in fact according to one of their properties, which is NOT the key and may be duplicated between different objects) .net provides two classes (SortedDictionnary and SortedList), and both are some kind of Dictionaries. The only difference (AFAIK) is that SortedDictionnary uses a binary tree to maintain its state whereas SortedList does not and is accessible via an index. I could achieve what I want using a List, and then using its Sort() method with a custom implementation of IComparer, but it wouldn't be time-efficient as I would sort the whole List each time I insert a new object, whereas a good SortedList would just insert the item at the right position. What I need is a SortedList class with a RefreshPosition(int index) to move only the changed (or inserted) object rather than resorting the whole list each time an object inside changes. Am I missing something obvious ?

    Read the article

  • Create and populate two-dimensional array in Scala

    - by ~asteinlein
    What's the recommended way of creating a pre-populated two-dimensional array in Scala? I've got the following code: val map = for { x <- (1 to size).toList } yield for { y <- (1 to size).toList } yield (x, y) How do I make an array instead of list? Replacing .toList with .toArray doesn't compile. And is there a more concise or readable way of doing this than the nested for expressions?

    Read the article

  • Quickly retrieve the subset of properties used in a huge collection in C#

    - by ccornet
    I have a huge Collection (which I can cast as an enumerable using OfType<()) of objects. Each of these objects has a Category property, which is drawn from a list somewhere else in the application. This Collection can reach sizes of hundreds of items, but it is possible that only, say, 6/30 of the possible Categories are actually used. What is the fastest method to find these 6 Categories? The size of the huge Collection discourages me from just iterating across the entire thing and returning all unique values, so is there a faster method of accomplishing this? Ideally I'd collect the categories into a List.

    Read the article

  • Unchecked call to compareTo

    - by Dave Jarvis
    Background Create a Map that can be sorted by value. Problem The code executes as expected, but does not compile cleanly: http://pastebin.com/bWhbHQmT The syntax for passing Comparable as a generic parameter along to the Map.Entry<K, V> (where V must be Comparable?) -- so that the (Comparable) typecast shown in the warning can be dropped -- eludes me. Warning Compiler's cantankerous complaint: SortableValueMap.java:24: warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable return ((Comparable)entry1.getValue()).compareTo( entry2.getValue() ); Question How can the code be changed to compile without any warnings (without suppressing them while compiling with -Xlint:unchecked)? Related TreeMap sort by value How to sort a Map on the values in Java? http://paaloliver.wordpress.com/2006/01/24/sorting-maps-in-java/ Thank you!

    Read the article

  • VB.net: Is my Thread Safe List Solution actually safe?

    - by Shiftbit
    I've added teh following Extensions to my Project in order to create a thread safe list: Extensions If I want to conduct a simple operation on my list <Extension()> _ Public Sub Action(Of T)(ByVal list As List(Of T), ByVal action As Action(Of List(Of T))) SyncLock (list) action(list) End SyncLock End Sub If I want to pass it more than one parameter I could simply extend it with more items... <Extension()> _ Public Sub Action(Of T)(ByVal list As List(Of T), ByVal action As Action(Of List(Of T), T), ByVal item As T) SyncLock (list) Action(list, item) End SyncLock End Sub Actions I have created the following Action Examples: Private Sub Read(Of T)(ByVal list As List(Of T)) Console.WriteLine("Read") For Each item As T In list Console.WriteLine(item.ToString) Thread.Sleep(10) Next End Sub and also one that takes a parameter: Private Sub Write(Of T)(ByVal list As List(Of T), ByVal item As T) Thread.Sleep(100) list.Add(item) Console.WriteLine("Write") End Sub Initiating Then in my various threads I will call my Actions with: list.Action(AddressOf Read) or list.Action(AddressOf Write2, 10) Are these Extenxion methods thread safe or do you have other recommendations?

    Read the article

  • How to change order in ordered+persisted collection?

    - by Jaroslav Záruba
    I just need to change order of items in a (previously persisted) ordered collection... I tried simply passing the re-arranged collection to a setter: after committing a transaction the collection is gone. Then I tried to clear() the existing collection and addAll() afterwards: clear() makes persistent manager to mark all the elements as deleted. (But obviously I would like to be able to work with the collection items in the very transaction.) (The collection is not in a default fetch group, so I tried the above also with the named fetch group added into the fetch plan. No luck.) This must be the most stupid question, but I ran out of ideas and I'm stuck here two days already. I swear I googled. :(

    Read the article

  • Best data-structure to use for two ended sorted list

    - by fmark
    I need a collection data-structure that can do the following: Be sorted Allow me to quickly pop values off the front and back of the list Remain sorted after I insert a new value Allow a user-specified comparison function, as I will be storing tuples and want to sort on a particular value Thread-safety is not required Optionally allow efficient haskey() lookups (I'm happy to maintain a separate hash-table for this though) My thoughts at this stage are that I need a priority queue and a hash table, although I don't know if I can quickly pop values off both ends of a priority queue. I'm interested in performance for a moderate number of items (I would estimate less than 200,000). Another possibility is simply maintaining an OrderedDictionary and doing an insertion sort it every-time I add more data to it. Furthermore, are there any particular implementations in Python. I would really like to avoid writing this code myself.

    Read the article

  • Recreating a Dictionary from an IEnumerable

    - by learnerplates
    But some of the callers is the Dictionary's TryGetValue and ContainsKey and so require the result of the method to be a Dictionary, how can I convert the IEnumerable into a Dictionary so that I can use TryGetValue ? I've a method which at present returns an IEnumerable. I want to make it more generic by making it return an IEnumerable. method: public IEnumerable<KeyValuePair<string, ArrayList>> GetComponents() { // ... yield return new KeyValuePair<string, ArrayList>(t.Name, controlInformation); } caller: Dictionary<string, ArrayList> actual = target.GetComponents(); actual.ContainsKey("something");

    Read the article

  • Java: How to workaround the lack of Equatable interface?

    - by java.is.for.desktop
    Hello, everyone! As far as I know, things such as SortedMap or SortedSet, use compareTo (rather than equals) on Comparable<?> types for checking equality (contains, containsKey). But what if certain types are equatable by concept, but not comparable? I have to declare a Comparator<?> and override the method int compareTo(T o1, To2). OK, I can return 0 for instances which are considered equal. But, for unqeual instances, what do I return when an order is not evident? Is the approach of using SortedMap or SortedSet on equatable but (by concept) not comparable types good anyway? Thank you! EDIT: I don't want to store things sorted, but would I use "usual" Map and Set, I couldn't "override" the equality-behavior. EDIT 2: Why I can't just override equals(...): I need to alter the equality-behavior of a foreign class. Can't edit it. EDIT 3: Just think of .NET: They have IEquatable interface which cat alter the equality-behavior without touching the comparable behavior.

    Read the article

  • Creating a blocking Queue<T> in .NET?

    - by spoon16
    I have a scenario where I have multiple threads adding to a queue and multiple threads reading from the same queue. If the queue reaches a specific size all threads that are filling the queue will be blocked on add until an item is removed from the queue. The solution below is what I am using right now and my question is: How can this be improved? Is there an object that already enables this behavior in the BCL that I should be using? internal class BlockingCollection<T> : CollectionBase, IEnumerable { //todo: might be worth changing this into a proper QUEUE private AutoResetEvent _FullEvent = new AutoResetEvent(false); internal T this[int i] { get { return (T) List[i]; } } private int _MaxSize; internal int MaxSize { get { return _MaxSize; } set { _MaxSize = value; checkSize(); } } internal BlockingCollection(int maxSize) { MaxSize = maxSize; } internal void Add(T item) { Trace.WriteLine(string.Format("BlockingCollection add waiting: {0}", Thread.CurrentThread.ManagedThreadId)); _FullEvent.WaitOne(); List.Add(item); Trace.WriteLine(string.Format("BlockingCollection item added: {0}", Thread.CurrentThread.ManagedThreadId)); checkSize(); } internal void Remove(T item) { lock (List) { List.Remove(item); } Trace.WriteLine(string.Format("BlockingCollection item removed: {0}", Thread.CurrentThread.ManagedThreadId)); } protected override void OnRemoveComplete(int index, object value) { checkSize(); base.OnRemoveComplete(index, value); } internal new IEnumerator GetEnumerator() { return List.GetEnumerator(); } private void checkSize() { if (Count < MaxSize) { Trace.WriteLine(string.Format("BlockingCollection FullEvent set: {0}", Thread.CurrentThread.ManagedThreadId)); _FullEvent.Set(); } else { Trace.WriteLine(string.Format("BlockingCollection FullEvent reset: {0}", Thread.CurrentThread.ManagedThreadId)); _FullEvent.Reset(); } } }

    Read the article

  • Iteration order of HashSet

    - by eljenso
    If every object added to a java.util.HashSet implements Object.equals() and Object.hashCode() in a deterministic fashion, is the iteration order over the HashSet guaranteed to be identical for every identical set of elements added, irrespective of the order in which they were added?

    Read the article

  • How to print all values of Vector[]

    - by terence6
    I have a Vector[] of Object type that stores my data. How to print all it's objects ? The code: private static Vector<Object[]> vector = new Vector<Object[]>(); int event=0; for(int i=0; i<10; i++){ vector.add( this.addToObject(System.currentTimeMillis(), event , "String") ); event++; } private Object[] addToObject(long t, int i,String s ){ Object[] o = new Object[4]; o[3] = s; o[2] = i; o[1] = "00000"; o[0] = t; return o; } printing public static void main(String[]args){ main m = new Main(); for(int i=0; i< m.vector.size(); i++){ } } And I'd like to get sth like this : 1202393057117 1 OOOOO String 1202393057117 2 OOOOO String 1202393057118 3 OOOOO String 1202393057118 4 OOOOO String 1202393057118 5 OOOOO String

    Read the article

  • Can I use foreach to return only a certain type from a collection?

    - by RoboShop
    If I enter the code below, I get an error. Basically, the foreach will break when it comes across a Control that isn't a label. foreach (Label currControl in this.Controls()) { ... } I have to do something like this. foreach (Control currControl in this.Controls()) { if(typeof(Label).Equals(currControl.GetType())){ ... } } can anyone think of a better way of doing it without me needing to check the type? Can I somehow get foreach to skip the objects that aren't Labels?

    Read the article

  • Hashtable is that fast

    - by Costa
    Hi s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]. Is the hash function of the java string, I assume the rest of languages is similar or close to this implementation. If we have hash-Table and a list of 50 elements. each element is 7 chars ABCDEF1, ABCDEF2, ABCDEF3..... ABCDEFn If each bucket of hashtable contains 5 strings (I think this function will make it one string per bucket, but let us assume it is 5). If we call col.Contains("ABCDEFn"); // will do 6 comparisons and discover the difference on the 7th. The hash-table will take around 70 operations (multiplication and additions) to get the hashcode and to compare with 5 strings in bucket. and BANG it found. For list it will take around 300 comparisons to find it. for the case that there is only 10 elements, the list will take around 70 operations but the Hashtable will take around 50 operations. and note that hashtable operations are more time consuming (it is multiplications). I conclude that HybirdDictionary in .Net probably is the best choice for that most cases that require Hashtable with unknown size, because it will let me use a list till the list becomes more than 10 elements. still need something like HashSet rather than a Dictionary of keys and values, I wonder why there is no HybirdSet!! So what do u think? Thanks

    Read the article

  • Testing a (big) collection retrieved from a db

    - by Bas
    I'm currently doing integration testing on a live database and I have the following sql statement: var date = DateTime.Parse("01-01-2010 20:30:00"); var result = datacontext.Repository<IObject>().Where(r => r.DateTime > date).First(); Assert.IsFalse(result.Finished); I need to test if the results retrieved from the statement, where the given date is less then the date of the object, have Finished set to False. I do not know how many results I get back and currently I'm getting the first object of the list and check if that object has Finished set to false. I know testing only the first item of the list is not valid testing, as a solution for that I could iterate through the list and check all items on Finished, but putting logic in a Test is kinda going against the concept of writing 'good' tests. So my question is: Does anyone have a good solution of how to properly test the results of this list?

    Read the article

  • Null-free "maps": Is a callback solution slower than tryGet()?

    - by David Moles
    In comments to "How to implement List, Set, and Map in null free design?", Steven Sudit and I got into a discussion about using a callback, with handlers for "found" and "not found" situations, vs. a tryGet() method, taking an out parameter and returning a boolean indicating whether the out parameter had been populated. Steven maintained that the callback approach was more complex and almost certain to be slower; I maintained that the complexity was no greater and the performance at worst the same. But code speaks louder than words, so I thought I'd implement both and see what I got. The original question was fairly theoretical with regard to language ("And for argument sake, let's say this language don't even have null") -- I've used Java here because that's what I've got handy. Java doesn't have out parameters, but it doesn't have first-class functions either, so style-wise, it should suck equally for both approaches. (Digression: As far as complexity goes: I like the callback design because it inherently forces the user of the API to handle both cases, whereas the tryGet() design requires callers to perform their own boilerplate conditional check, which they could forget or get wrong. But having now implemented both, I can see why the tryGet() design looks simpler, at least in the short term.) First, the callback example: class CallbackMap<K, V> { private final Map<K, V> backingMap; public CallbackMap(Map<K, V> backingMap) { this.backingMap = backingMap; } void lookup(K key, Callback<K, V> handler) { V val = backingMap.get(key); if (val == null) { handler.handleMissing(key); } else { handler.handleFound(key, val); } } } interface Callback<K, V> { void handleFound(K key, V value); void handleMissing(K key); } class CallbackExample { private final Map<String, String> map; private final List<String> found; private final List<String> missing; private Callback<String, String> handler; public CallbackExample(Map<String, String> map) { this.map = map; found = new ArrayList<String>(map.size()); missing = new ArrayList<String>(map.size()); handler = new Callback<String, String>() { public void handleFound(String key, String value) { found.add(key + ": " + value); } public void handleMissing(String key) { missing.add(key); } }; } void test() { CallbackMap<String, String> cbMap = new CallbackMap<String, String>(map); for (int i = 0, count = map.size(); i < count; i++) { String key = "key" + i; cbMap.lookup(key, handler); } System.out.println(found.size() + " found"); System.out.println(missing.size() + " missing"); } } Now, the tryGet() example -- as best I understand the pattern (and I might well be wrong): class TryGetMap<K, V> { private final Map<K, V> backingMap; public TryGetMap(Map<K, V> backingMap) { this.backingMap = backingMap; } boolean tryGet(K key, OutParameter<V> valueParam) { V val = backingMap.get(key); if (val == null) { return false; } valueParam.value = val; return true; } } class OutParameter<V> { V value; } class TryGetExample { private final Map<String, String> map; private final List<String> found; private final List<String> missing; public TryGetExample(Map<String, String> map) { this.map = map; found = new ArrayList<String>(map.size()); missing = new ArrayList<String>(map.size()); } void test() { TryGetMap<String, String> tgMap = new TryGetMap<String, String>(map); for (int i = 0, count = map.size(); i < count; i++) { String key = "key" + i; OutParameter<String> out = new OutParameter<String>(); if (tgMap.tryGet(key, out)) { found.add(key + ": " + out.value); } else { missing.add(key); } } System.out.println(found.size() + " found"); System.out.println(missing.size() + " missing"); } } And finally, the performance test code: public static void main(String[] args) { int size = 200000; Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i < size; i++) { String val = (i % 5 == 0) ? null : "value" + i; map.put("key" + i, val); } long totalCallback = 0; long totalTryGet = 0; int iterations = 20; for (int i = 0; i < iterations; i++) { { TryGetExample tryGet = new TryGetExample(map); long tryGetStart = System.currentTimeMillis(); tryGet.test(); totalTryGet += (System.currentTimeMillis() - tryGetStart); } System.gc(); { CallbackExample callback = new CallbackExample(map); long callbackStart = System.currentTimeMillis(); callback.test(); totalCallback += (System.currentTimeMillis() - callbackStart); } System.gc(); } System.out.println("Avg. callback: " + (totalCallback / iterations)); System.out.println("Avg. tryGet(): " + (totalTryGet / iterations)); } On my first attempt, I got 50% worse performance for callback than for tryGet(), which really surprised me. But, on a hunch, I added some garbage collection, and the performance penalty vanished. This fits with my instinct, which is that we're basically talking about taking the same number of method calls, conditional checks, etc. and rearranging them. But then, I wrote the code, so I might well have written a suboptimal or subconsicously penalized tryGet() implementation. Thoughts?

    Read the article

  • fail-fast iterator

    - by joy
    I get this definition : As name suggest fail-fast Iterators fail as soon as they realized that structure of Collection has been changed since iteration has begun. what it mean by since iteration has begun? is that mean after Iterator it=set.iterator() this line of code? public static void customize(BufferedReader br) throws IOException{ Set<String> set=new HashSet<String>(); // Actual type parameter added **Iterator it=set.iterator();**

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >