This presentation comes with many additional notes (pdf): http://de.slideshare.net/nicolayludwig/4-collections-algorithms-38613530
- Object-based vs. generic Collections
-- Generics Types in Java
- Sequential and associative Collections
- Associative Collections
-- Equivalence-based associative Collections: .Net's SortedDictionary
-- Operations on .Net's IDictionarys
-- Comparison and Implementation of .Net's Interfaces IComparable and IComparer
The document discusses new features in C#2 for iterators and nullable types. It describes how C#2 introduced iterator blocks using the "yield" keyword to more easily implement iterators. This allows iterators to be defined without having to implement interfaces. The document also explains how C#2 introduced the Nullable type to allow value types to represent null values. It can be used with the ? syntax sugar and supports lifting operators to work with nullable types.
(7) c sharp introduction_advanvced_features_part_iiNico Ludwig
This document provides an overview of advanced C# features including collections, delegates, events, custom attributes, and reflection. It discusses how generic collections allow type-safe storage and access of elements compared to object-based collections. Delegates are described as a way to pass methods as arguments to other methods. Events allow objects to notify observers of state changes through delegate-based callbacks. Custom attributes provide a way to annotate types and members with metadata, and reflection enables examining types at runtime to access this metadata and other structural details.
(7) c sharp introduction_advanvced_features_part_iiNico Ludwig
This presentation comes with many additional notes (pdf): http://de.slideshare.net/nicolayludwig/7-c-sharp-introductionadvanvcedfeaturespartii-38640489
Check out these exercises: http://de.slideshare.net/nicolayludwig/6-7-c-sharp-introductionadvancedfeaturespartipartiiexercises
- Object-based and generic Collections
- Delegates and Events
- Custom Attributes
- Reflection
Objective-C to Swift - Swift Cloud Workshop 3Randy Scovil
The document provides an overview of the Swift programming language from the perspective of an instructor who has taught both Objective-C and Swift courses. It covers key differences between Swift and Objective-C like value types, optionals, error handling, and the Codable protocol. The instructor observes that while some aspects of Swift are easier to learn, other advanced features can be more difficult. Examples throughout demonstrate language concepts.
This presentation comes with many additional notes (pdf): http://de.slideshare.net/nicolayludwig/4-collections-algorithms-38613530
- Object-based vs. generic Collections
-- Generics Types in Java
- Sequential and associative Collections
- Associative Collections
-- Equivalence-based associative Collections: .Net's SortedDictionary
-- Operations on .Net's IDictionarys
-- Comparison and Implementation of .Net's Interfaces IComparable and IComparer
The document discusses new features in C#2 for iterators and nullable types. It describes how C#2 introduced iterator blocks using the "yield" keyword to more easily implement iterators. This allows iterators to be defined without having to implement interfaces. The document also explains how C#2 introduced the Nullable type to allow value types to represent null values. It can be used with the ? syntax sugar and supports lifting operators to work with nullable types.
(7) c sharp introduction_advanvced_features_part_iiNico Ludwig
This document provides an overview of advanced C# features including collections, delegates, events, custom attributes, and reflection. It discusses how generic collections allow type-safe storage and access of elements compared to object-based collections. Delegates are described as a way to pass methods as arguments to other methods. Events allow objects to notify observers of state changes through delegate-based callbacks. Custom attributes provide a way to annotate types and members with metadata, and reflection enables examining types at runtime to access this metadata and other structural details.
(7) c sharp introduction_advanvced_features_part_iiNico Ludwig
This presentation comes with many additional notes (pdf): http://de.slideshare.net/nicolayludwig/7-c-sharp-introductionadvanvcedfeaturespartii-38640489
Check out these exercises: http://de.slideshare.net/nicolayludwig/6-7-c-sharp-introductionadvancedfeaturespartipartiiexercises
- Object-based and generic Collections
- Delegates and Events
- Custom Attributes
- Reflection
Objective-C to Swift - Swift Cloud Workshop 3Randy Scovil
The document provides an overview of the Swift programming language from the perspective of an instructor who has taught both Objective-C and Swift courses. It covers key differences between Swift and Objective-C like value types, optionals, error handling, and the Codable protocol. The instructor observes that while some aspects of Swift are easier to learn, other advanced features can be more difficult. Examples throughout demonstrate language concepts.
Quick Scala is an overview document that summarizes:
- Scala is a pure object-oriented and functional language that runs on the JVM, with static types and type inference.
- It supports classes, traits, functions, concurrency with actors, and pattern matching.
- The document outlines Scala's basic syntax including objects, classes, methods, and data types, as well as features like strings, arrays, collections, traits, exception handling and extractors.
C++ - Constructors,Destructors, Operator overloading and Type conversionHashni T
This document discusses constructors and destructors in C++. It begins by defining constructors as special methods that are automatically called when an object is created. Constructors initialize class data members and have the same name as the class. Destructors are used to destroy objects and clean up memory. The document then covers topics like parameterized constructors, copy constructors, dynamic constructors, characteristics of constructors and destructors, and operator overloading and type conversions.
The document outlines an agenda for learning core Java concepts over 15 sections. It introduces key Java topics like primitive data types, variables, arrays, control flow statements, classes and objects, inheritance, polymorphism, exceptions, strings and characters, files and streams, and generic collections. The agenda also covers defining classes and methods, passing arguments, encapsulation, and memory concepts like objects, references, and the heap.
The document discusses Java programming concepts like comments, classes, methods, and user input. It provides explanations and examples of:
1) How comments are used in Java and the different types of comments.
2) The basic structure of a Java class including the main method that acts as the entry point.
3) How the System.out.println method prints output and how user input can be accepted using the Scanner class.
its all about java variable.....you may also learn about various data type by this slide. freshers become helpful to read out this.this slides also may helpful in your varsity java course class .in this slide there is vast discussion about java variable
This document provides an overview of key Java concepts including:
- Classes define blueprints for objects with states and behaviors.
- Objects are instances of classes that store their unique state in fields and expose behaviors through methods.
- Other concepts covered include variables, primitive data types, arrays, operators, control flow statements, passing arguments to methods, and the difference between passing primitive and reference types. The document serves as an introduction for learning Java.
This document provides information on variables, data types, and keywords in C# programming. It discusses the differences between static and normal variables, with static variables allocating memory in the class and maintaining their value until the application closes. Different data types are described like integral, floating point, and nullable types. Value, reference, and pointer data types are also explained. The document contains code examples demonstrating static and normal variables as well as printing the limits of different data types. Keywords in C# that cannot be used as identifiers are listed.
Python uses call by object reference for calling functions. Variables in Python refer to objects, not memory locations, so calling a function passes the object reference rather than a copy. Decorators allow functions to be passed as arguments or returned from other functions. Generators provide an easy way to define iterators by using the yield keyword. Magic methods allow customizing class behavior by overriding special method names. Virtual environments isolate Python environments for testing packages without affecting the system Python installation.
The document provides an overview of core Java basics including data types, operators, keywords, comments, literals, type conversion and casting, classes and objects, constructors, class variables, constants, and static methods. It discusses primitive data types like int, float, boolean and their ranges. It also covers operators precedence and arithmetic, logical, and assignment operators.
This document discusses the Comparable and Comparator interfaces in Java. Comparable allows an object to compare itself to another object, while Comparator allows two objects to be compared to each other based on arbitrary criteria. The document provides examples of implementing these interfaces to allow collections like lists to be sorted. It also discusses function objects and anonymous classes in Java.
This document discusses TypeScript and its advantages over JavaScript. TypeScript is a superset of JavaScript that adds type safety and catches errors earlier. It allows for static and strong typing through features like type inference, interfaces, and unions. While TypeScript adds complexity, it encourages cleaner code and helps catch bugs earlier by validating types. The document provides examples of basic types, interfaces, type aliases, and how to add typing to React components. Overall, the document presents a positive case for learning TypeScript despite initial costs in order to write better code.
This document provides an introduction and overview of the C# programming language. It discusses prerequisites, learning objectives, and the agenda. It covers Hello World examples, design goals of C#, types including value types and reference types, program structure, statements, operators, and using Visual Studio and the .NET framework. Key topics are the unified type system in C#, value types vs reference types, boxing and unboxing, predefined types like integers and strings, and object being the root type.
Actors are a model of concurrent computation that treats isolated "actors" as the basic unit. Actors communicate asynchronously by message passing and avoid shared state. This model addresses issues in Java's thread/lock model like deadlocks. In Gpars, actors include stateless actors like DynamicDispatchActor and stateful actors like DefaultActor. The demo shows examples of stateless and stateful actors in Gpars.
This document discusses the java.util.StringTokenizer class which allows breaking a string into tokens. It describes the constructors and methods of StringTokenizer, including how to count, check for, and retrieve the next token. An example program demonstrates its use by tokenizing a sample string and outputting the results.
The document discusses the eight primitive data types in Java - boolean, char, byte, short, int, long, float, and double. It explains what each type is used for, their possible value ranges, and when to use each type. Key points covered include int being the preferred integer type, double the preferred real number type, and the importance of declaring variables before use and giving them initial values.
The document discusses several new features introduced in Java 5 that aim to simplify Java development:
1) New collection classes and concurrent utilities were added to the Java library to provide more robust functionality out of the box.
2) Covariant returns allow overriding methods to have a more specific return type as long as it extends the original return type.
3) Enhanced for loops (foreach loops) improve readability when iterating over collections by eliminating the need for iterators.
4) Autoboxing and unboxing automatically convert between primitives and their corresponding wrapper types.
The document provides an overview of Strings and StringBuilders in Java. It discusses Strings as immutable objects and how StringBuilders can be more efficient for modifying strings. It also covers common String and StringBuilder methods, when to use each, and exceptions in Java using try/catch blocks.
The document provides an overview of the basics of C# 2008 .NET 3.0/3.5, including the basic structure of a C# program, namespaces, classes, methods, variables, data types, operators, flow control, arrays, namespaces, console input/output, and comments. It discusses key concepts such as object-oriented programming fundamentals, console applications in Visual Studio 2008, and more advanced topics such as checked and unchecked operators.
La costa asturiana se caracteriza por sus acantilados, calas y pueblos marineros como Tapia de Casariego, Luarca, Cudillero y Llanes, este último el más turístico. Las ciudades principales son Oviedo, capital cultural y cuna de Fernando Alonso; Gijón, con su ambiente veraniego; y Avilés, antigua ciudad industrial que ahora recupera su ría. Los paisajes naturales como los Picos de Europa y los parques de Somiedo y Fuentes del Narcea también atraen turismo.
Quick Scala is an overview document that summarizes:
- Scala is a pure object-oriented and functional language that runs on the JVM, with static types and type inference.
- It supports classes, traits, functions, concurrency with actors, and pattern matching.
- The document outlines Scala's basic syntax including objects, classes, methods, and data types, as well as features like strings, arrays, collections, traits, exception handling and extractors.
C++ - Constructors,Destructors, Operator overloading and Type conversionHashni T
This document discusses constructors and destructors in C++. It begins by defining constructors as special methods that are automatically called when an object is created. Constructors initialize class data members and have the same name as the class. Destructors are used to destroy objects and clean up memory. The document then covers topics like parameterized constructors, copy constructors, dynamic constructors, characteristics of constructors and destructors, and operator overloading and type conversions.
The document outlines an agenda for learning core Java concepts over 15 sections. It introduces key Java topics like primitive data types, variables, arrays, control flow statements, classes and objects, inheritance, polymorphism, exceptions, strings and characters, files and streams, and generic collections. The agenda also covers defining classes and methods, passing arguments, encapsulation, and memory concepts like objects, references, and the heap.
The document discusses Java programming concepts like comments, classes, methods, and user input. It provides explanations and examples of:
1) How comments are used in Java and the different types of comments.
2) The basic structure of a Java class including the main method that acts as the entry point.
3) How the System.out.println method prints output and how user input can be accepted using the Scanner class.
its all about java variable.....you may also learn about various data type by this slide. freshers become helpful to read out this.this slides also may helpful in your varsity java course class .in this slide there is vast discussion about java variable
This document provides an overview of key Java concepts including:
- Classes define blueprints for objects with states and behaviors.
- Objects are instances of classes that store their unique state in fields and expose behaviors through methods.
- Other concepts covered include variables, primitive data types, arrays, operators, control flow statements, passing arguments to methods, and the difference between passing primitive and reference types. The document serves as an introduction for learning Java.
This document provides information on variables, data types, and keywords in C# programming. It discusses the differences between static and normal variables, with static variables allocating memory in the class and maintaining their value until the application closes. Different data types are described like integral, floating point, and nullable types. Value, reference, and pointer data types are also explained. The document contains code examples demonstrating static and normal variables as well as printing the limits of different data types. Keywords in C# that cannot be used as identifiers are listed.
Python uses call by object reference for calling functions. Variables in Python refer to objects, not memory locations, so calling a function passes the object reference rather than a copy. Decorators allow functions to be passed as arguments or returned from other functions. Generators provide an easy way to define iterators by using the yield keyword. Magic methods allow customizing class behavior by overriding special method names. Virtual environments isolate Python environments for testing packages without affecting the system Python installation.
The document provides an overview of core Java basics including data types, operators, keywords, comments, literals, type conversion and casting, classes and objects, constructors, class variables, constants, and static methods. It discusses primitive data types like int, float, boolean and their ranges. It also covers operators precedence and arithmetic, logical, and assignment operators.
This document discusses the Comparable and Comparator interfaces in Java. Comparable allows an object to compare itself to another object, while Comparator allows two objects to be compared to each other based on arbitrary criteria. The document provides examples of implementing these interfaces to allow collections like lists to be sorted. It also discusses function objects and anonymous classes in Java.
This document discusses TypeScript and its advantages over JavaScript. TypeScript is a superset of JavaScript that adds type safety and catches errors earlier. It allows for static and strong typing through features like type inference, interfaces, and unions. While TypeScript adds complexity, it encourages cleaner code and helps catch bugs earlier by validating types. The document provides examples of basic types, interfaces, type aliases, and how to add typing to React components. Overall, the document presents a positive case for learning TypeScript despite initial costs in order to write better code.
This document provides an introduction and overview of the C# programming language. It discusses prerequisites, learning objectives, and the agenda. It covers Hello World examples, design goals of C#, types including value types and reference types, program structure, statements, operators, and using Visual Studio and the .NET framework. Key topics are the unified type system in C#, value types vs reference types, boxing and unboxing, predefined types like integers and strings, and object being the root type.
Actors are a model of concurrent computation that treats isolated "actors" as the basic unit. Actors communicate asynchronously by message passing and avoid shared state. This model addresses issues in Java's thread/lock model like deadlocks. In Gpars, actors include stateless actors like DynamicDispatchActor and stateful actors like DefaultActor. The demo shows examples of stateless and stateful actors in Gpars.
This document discusses the java.util.StringTokenizer class which allows breaking a string into tokens. It describes the constructors and methods of StringTokenizer, including how to count, check for, and retrieve the next token. An example program demonstrates its use by tokenizing a sample string and outputting the results.
The document discusses the eight primitive data types in Java - boolean, char, byte, short, int, long, float, and double. It explains what each type is used for, their possible value ranges, and when to use each type. Key points covered include int being the preferred integer type, double the preferred real number type, and the importance of declaring variables before use and giving them initial values.
The document discusses several new features introduced in Java 5 that aim to simplify Java development:
1) New collection classes and concurrent utilities were added to the Java library to provide more robust functionality out of the box.
2) Covariant returns allow overriding methods to have a more specific return type as long as it extends the original return type.
3) Enhanced for loops (foreach loops) improve readability when iterating over collections by eliminating the need for iterators.
4) Autoboxing and unboxing automatically convert between primitives and their corresponding wrapper types.
The document provides an overview of Strings and StringBuilders in Java. It discusses Strings as immutable objects and how StringBuilders can be more efficient for modifying strings. It also covers common String and StringBuilder methods, when to use each, and exceptions in Java using try/catch blocks.
The document provides an overview of the basics of C# 2008 .NET 3.0/3.5, including the basic structure of a C# program, namespaces, classes, methods, variables, data types, operators, flow control, arrays, namespaces, console input/output, and comments. It discusses key concepts such as object-oriented programming fundamentals, console applications in Visual Studio 2008, and more advanced topics such as checked and unchecked operators.
La costa asturiana se caracteriza por sus acantilados, calas y pueblos marineros como Tapia de Casariego, Luarca, Cudillero y Llanes, este último el más turístico. Las ciudades principales son Oviedo, capital cultural y cuna de Fernando Alonso; Gijón, con su ambiente veraniego; y Avilés, antigua ciudad industrial que ahora recupera su ría. Los paisajes naturales como los Picos de Europa y los parques de Somiedo y Fuentes del Narcea también atraen turismo.
El documento resume los principales peligros de Internet para los menores como el ciberacoso y la ciberprostitución. Explica que los menores conocen el uso de la tecnología pero no el buen uso y carecen de valores, mientras que los padres desconocen cómo funcionan las redes sociales. Propone formar a padres, menores y profesores sobre el uso seguro de Internet y las nuevas tecnologías.
El Paso City Council 09.09.14 Agenda Item 15.2: Osab Cement Lake Recommendationepdevelopment
Discussion and action on a recommendation from the Open Space Advisory Board that the City Council direct City staff to initiate preservation efforts of the “Cement Lake Wetlands," in coordination with the Texas Department of Transportation, to ensure its permanent preservation.
All Districts
First, someone will give an overview of air quality concerns and current statistics. Next, there will be a presentation of propane buses and how they fit with improving air
quality and cutting costs. Next, administrators will talk about how their districts have incorporated language into their RFP and contracts to encourage more environmentally friendly buses for their students.
This document contains a list of questions and statements about science, health, and nature topics for children. Some examples include questions about whether plants can grow in egg shells, what pumpkin seeds look like, the different types of music, how to make bubbles, and labeling rocks by size. Additionally, it discusses the importance of washing hands and teeth, getting plenty of rest, eating a variety of healthy foods, drinking water, and using water for purposes beyond cleaning to stay healthy.
Typescript is a strict syntactical superset of JavaScript that adds type safety. It allows defining type annotations for variables, functions, objects, and function return values to catch errors. Typescript uses a static and structural type system. Its types include primitives, objects, arrays, functions, classes, generics, and utility types. Typescript code compiles to JavaScript, so it doesn't change runtime behavior but can catch errors earlier.
The document provides an overview of ActionScript 3.0 fundamentals including the ActionScript Virtual Machine, data types, classes, inheritance, interfaces, and object-oriented programming concepts in ActionScript. It discusses topics such as variables, functions, conditional statements, loops, scope, packages, namespaces, and more. The document is intended as educational material for learning the basics of the ActionScript 3.0 programming language.
C# is a strongly typed language where all variables and expressions have a type that provides information like storage size, value range, members, and more. The compiler uses types to ensure type-safe operations. Built-in types include integers, floats, Booleans, strings, and objects. Custom types can be created using structs, classes, interfaces, and enums. Types in the .NET Framework are either value types, which are stored inline, or reference types, which are stored on the heap. Generic types allow code reuse by specifying placeholders for concrete types.
This document provides an overview and agenda for a lesson on .NET Framework fundamentals. It covers using value types and reference types, constructing classes through inheritance, interfaces, generics and events/delegates. It also discusses converting between types through boxing, unboxing, parsing and exceptions. The lesson aims to help manage data using .NET system types and control component interactions.
Java Generics Introduction - Syntax Advantages and PitfallsRakesh Waghela
This document provides an overview of Java generics. It discusses what generics are, their history and motivation, how they improved type safety over non-generic collections. Key points covered include the Collections Framework being rewritten using generics, concepts like type erasure and type parameters. It also discusses bounded types, wildcards and examples of generic classes, methods and interfaces.
This presentation comes with many additional notes (pdf): http://de.slideshare.net/nicolayludwig/2-collections-algorithms-38612937
- Arrays revisited
- Value and Reference Semantics of Elements
- A Way to categorize Collections
- Indexed Collections
-- Lists
-- Basic Features and Examples
-- Size and Capacity
This presentation comes with many additional notes (pdf): http://de.slideshare.net/nicolayludwig/6-collections-algorithms-38614039
- Producing Collection Objects
- Immutable Collections and defense Copies
- Empty Collections
- Tuples as pseudo Collections
- Filling Collections with structured Data
- Collections abstracting Data Processing: Stack and Queue
- Kung Fu beyond Collections: .Net's LINQ and Java's Streams
The document provides an overview of a two-day training course on C# scripting for an iX HMI solution. Day 1 covers basic C# concepts like variables, data types, flow control, methods, exceptions, arrays, and debugging. Day 2 focuses on scripting specifically for the iX platform, including accessing tags, screens, services, and more. Specific topics covered include script modules, events, file access, timers, serial ports, and referencing external assemblies.
The document discusses generics in Java. It introduces key terms related to generics like parameterized types, actual type parameters, formal type parameters, raw types, and wildcard types. It advises developers to avoid using raw types in new code and instead use parameterized types or wildcard types to maintain type safety. It also recommends eliminating all unchecked warnings from code by resolving the issues, and only suppressing warnings when absolutely necessary and the code has been proven type-safe.
This document provides an overview of several Java generics features including: generics allow compile-time type safety for collections without casting; the enhanced for loop automates use of iterators to avoid errors; autoboxing/unboxing avoids manual conversion between primitive types and wrapper types; typesafe enums provide benefits of the typesafe enum pattern; and examples of using generics with classes, methods, and collections.
Typescript is a superset of JavaScript that adds optional static typing and classes. It was created by Microsoft in 2010 and the first version was released in 2012. Although initially not widely adopted due to lack of IDE support, Typescript has grown in popularity over time. It provides benefits like type safety, IDE autocompletion, and catch bugs early. Typescript code compiles to plain JavaScript.
This document is an e-book that introduces LINQ (Language Integrated Query) in 11 parts. It explains what LINQ is, its benefits over previous approaches, and how to query different data sources like arrays, XML, and SQL databases using LINQ. It also discusses why generic types are needed for LINQ and provides examples of querying generic collections.
- Arrays revisited
- Value and Reference Semantics of Elements
- A Way to categorize Collections
- Indexed Collections
-- Lists
-- Basic Features and Examples
-- Size and Capacity
- Producing Collection Objects
- Immutable Collections and defense Copies
- Empty Collections
- Tuples as pseudo Collections
- Filling Collections with structured Data
- Collections abstracting Data Processing: Stack and Queue
- Kung Fu beyond Collections: .Net's LINQ and Java's Streams
The document provides an overview of the C programming language. It discusses that C is a general purpose, procedural language developed in 1972 at Bell Labs. C is a middle-level language as it allows programming at both high-level and assembly-level. Key aspects of C covered include data types, variables, operators, functions, arrays, pointers, memory management, and file handling. The document also provides examples of various C programming concepts.
This document provides information on various .NET and C# concepts:
1. It begins with an example C# program that multiplies two numbers and prints the result, demonstrating basic program structure and comments.
2. It then covers identifiers, keywords, single-line and multi-line comments in C#, and the differences between value types and reference types.
3. The document concludes by discussing object-oriented programming concepts in C# like classes, constructors, destructors, methods, inheritance, polymorphism, abstraction, interfaces, and abstract classes.
This set of slides introduces the reader to a subset of the C++ Standard Library called the Standard Template Library (STL). The STL provides a collection of parameterized containers and algorithms, and it is the most successful example of an approach to programming called generic programming. In this presentation, we aim at studying the ideals and concepts of the STL by re-implementing small parts of the library. Specifically, we first show how we can discover requirements on types in order to devise generic algorithms. Then, we focus on how to make algorithms independent of containers through the pivotal abstraction of iterators. To this end, we replicate the standard algorithm for finding the minimum in a sequence (min_element), which we subsequently match with a custom forward iterator over intrusive linked lists of integers. Finally, we see how function objects can be used to customize containers and algorithms alike. This allows us to deepen our understanding of ordering relations, and, in particular, to introduce the concept of strict weak orderings.
(4) cpp automatic arrays_pointers_c-stringsNico Ludwig
Check out these exercises: http://de.slideshare.net/nicolayludwig/4-cpp-automatic-arrayspointerscstringsexercises-38510502
- Pointers: Call by Value versus Call by Reference
- Automatic Arrays
- Arrays and Pointer Decay
- Pointers to Pointers
- C-strings as Arrays and their Memory Representation
- Basic C-string Functions
Python internals and how they affect your code - kasra ahmadvandirpycon
Python internals and how they may affect code. The document discusses various Python internals including objects, values and types, string interning, peephole optimizations, and internal types like code objects and frame objects. It also covers comparisons between different data types and some internal optimization tips.
Ctypes provides an easy way to extend Python with functions from C libraries without needing to write C code or dependencies like SWIG. It works by dynamically loading shared libraries and allowing Python functions to call C functions. Ctypes abstracts away the complexities of type conversions and memory management to make the process simple. Developers can write Python callback functions, define C structures and unions in Python, and interface with C libraries using just a few lines of Python code. This makes ctypes a popular modern alternative for creating Python bindings for C code.
Von Gleichungen zu Funktionen
Überblick über ganzrationale Funktionen
Koordinatensysteme für Graphen ganzrationaler Funktionen mit Excels Liniendiagrammen erstellen
Einfache Analyse ganzrationaler Funktionen anhand deren Graphen
Von linearen zu quadratischen Gleichungssystemen
Verschiedene Möglichkeiten quadratische Gleichungssysteme grafisch zu lösen
Koordinatensysteme für quadratische Graphen mit Excels Liniendiagrammen erstellen und Gleichungen damit grafisch lösen
Grafische Interpretation der Lösungen von Normalparabel-Gerade Kombinationen
Diagramme
Einführung linearer Gleichungssysteme mit zwei Unbekannten
Rechnerische und grafische Lösung linearer Gleichungssysteme
Wertetabellen mit Excel erstellen
Koordinatensysteme und lineare Graphen mit Excels Liniendiagrammen erstellen und Gleichungen damit grafisch lösen
Mit großen Tabellen arbeiten
Sortieren und Filtern
Objekte einfügen
Formeln und rechnen mit Excel, insbesondere Zahlen und Textbearbeitung
Relative und absolute Zellbezüge
Funktionen: SUMME(), ANZAHL(), MIN(), MAX(), MITTELWERT(), JETZT(), HEUTE(), ZUFALLSZAHL(), PI() und SUMMEWENN()
Mathematische Probleme in Tabellenform
Geschichtliche Entwicklung
Grundlegende Konzepte und Begriffe in Excel
Selektion, Dateneingabe und Datentypen
Zellformatierung und Inhaltsformatierung
This document discusses the history and evolution of graphical user interfaces (GUIs) in web browsers. It begins by explaining the concepts of vector-based and raster-based graphics. It then describes early approaches using bare HTML pages, which felt like navigation rather than a true application. Plugins were introduced to provide richer content but had problems with resources, installation, and security. Finally, the document introduces HTML5 Canvas as a solution for continuous, event-driven drawing without plugins, allowing single-page web applications.
The document discusses different approaches to drawing graphics on a computer screen, including raster-based and vector-based graphics. It focuses on raster-based drawing APIs and their evolution from native platform-specific APIs to platform-independent APIs in web browsers. Key developments included the use of browser plugins, problems with plugins, and the introduction of HTML5 Canvas which enables interactive drawing in browsers without plugins.
- Wires and Bulbs
- Batch Processing
- Terminal and Mainframe
- From the Command-Line to Killer Applications
- Vector Displays and Raster Displays
- Color Displays
- The Mouse and the Takeoff of Interactivity
- The Desktop Metaphor
- Wires and Bulbs
- Batch Processing
- Terminal and Mainframe
- From the Command-Line to Killer Applications
- Vector Displays and Raster Displays
- Color Displays
- The Mouse and the Takeoff of Interactivity
- The Desktop Metaphor
This document discusses new features in C# 4 including home-brew dynamic dispatch using the DynamicObject class. It allows implementing custom dynamic behavior by overriding methods like TryInvokeMember. The document also covers hosting scripting languages with the Dynamic Language Runtime (DLR), including IronPython, IronRuby, and IronScheme. Dynamic dispatch enables seamless collaboration and controlled isolation between .NET and DLR-based languages.
This document discusses new features in C# 4 related to dynamic coding. It describes how dynamic typing allows easier COM automation without needing interop types. Anonymous type instances can now be passed to methods using dynamic parameters. The document also discusses dynamic objects in JavaScript and how ExpandoObjects in .NET allow objects to have dynamically added and modified properties at runtime similar to dynamic objects in JavaScript.
This document discusses the Dynamic Language Runtime (DLR) and dynamic coding features in C# 4. It provides an overview of the DLR and how it allows interoperability between statically and dynamically typed languages on the .NET framework. The DLR transforms dynamic operations in C# into calls to the DLR at compile time and handles dynamic dispatch at runtime. It uses expression trees to represent operations in a language-agnostic way and caches binding results for improved performance.
This document discusses new features related to dynamic programming in C# 4. It begins by explaining why dynamic typing is an important new feature in .NET 4 due to increasing needs for interoperability. It then provides an overview of dynamic typing concepts like late binding and duck typing. The document shows how these concepts are implemented in VB for dynamic programming and how C#4 introduces dynamic typing capabilities through the new "dynamic" keyword and Dynamic Language Runtime (DLR) while still being a statically typed language. It discusses the basic syntax for using dynamics in C#4 and some restrictions.
This document summarizes new generic types and features in C# 4, including Lazy<T> for deferred initialization, tuples for ad-hoc data structures, and generic variance. Generic variance allows covariant and contravariant conversions between generic types to promote substitutability. It was enabled for interfaces and delegates in C# 4 through explicit variance declarations like "out T" and "in T". This improves type safety over arrays, which allow unsafe covariance in C#.
This document discusses LINQ (Language Integrated Query) features in C#, including introducing LINQ to Objects, basic query expressions for projection and selection, and anonymous types. It provides examples of how LINQ to Objects maps to extension methods, functional and declarative expressibility using LINQ, details about the LINQ translation process from query expressions to method calls, and examples of using anonymous types.
The document discusses LINQ and C# algorithms. It compares the C++ STL algorithm model to the .NET algorithm model using IEnumerable<T> sequences and extension methods. Key points include:
- The .NET model uses deferred execution via IEnumerable<T> sequences and iterator blocks, avoiding intermediate collections and allowing multiple operations to be chained.
- Extension methods allow algorithms to be expressed via method chaining in a declarative way rather than using loops.
- IEnumerable<T> sequences are more readable, uniform, and composable than the STL model due to chaining and deferred execution.
This document summarizes new C# 3.0 features including implicit typing, lambda expressions, and extension methods. Implicit typing allows declaring variables without an explicit type using the 'var' keyword. Lambda expressions provide a concise way to pass code as arguments using the '=>' operator. Extension methods allow adding methods to existing types without modifying them by defining methods in static classes that take the extended type as the first parameter.
Getting the Most Out of ScyllaDB Monitoring: ShareChat's TipsScyllaDB
ScyllaDB monitoring provides a lot of useful information. But sometimes it’s not easy to find the root of the problem if something is wrong or even estimate the remaining capacity by the load on the cluster. This talk shares our team's practical tips on: 1) How to find the root of the problem by metrics if ScyllaDB is slow 2) How to interpret the load and plan capacity for the future 3) Compaction strategies and how to choose the right one 4) Important metrics which aren’t available in the default monitoring setup.
Conversational agents, or chatbots, are increasingly used to access all sorts of services using natural language. While open-domain chatbots - like ChatGPT - can converse on any topic, task-oriented chatbots - the focus of this paper - are designed for specific tasks, like booking a flight, obtaining customer support, or setting an appointment. Like any other software, task-oriented chatbots need to be properly tested, usually by defining and executing test scenarios (i.e., sequences of user-chatbot interactions). However, there is currently a lack of methods to quantify the completeness and strength of such test scenarios, which can lead to low-quality tests, and hence to buggy chatbots.
To fill this gap, we propose adapting mutation testing (MuT) for task-oriented chatbots. To this end, we introduce a set of mutation operators that emulate faults in chatbot designs, an architecture that enables MuT on chatbots built using heterogeneous technologies, and a practical realisation as an Eclipse plugin. Moreover, we evaluate the applicability, effectiveness and efficiency of our approach on open-source chatbots, with promising results.
Introducing BoxLang : A new JVM language for productivity and modularity!Ortus Solutions, Corp
Just like life, our code must adapt to the ever changing world we live in. From one day coding for the web, to the next for our tablets or APIs or for running serverless applications. Multi-runtime development is the future of coding, the future is to be dynamic. Let us introduce you to BoxLang.
Dynamic. Modular. Productive.
BoxLang redefines development with its dynamic nature, empowering developers to craft expressive and functional code effortlessly. Its modular architecture prioritizes flexibility, allowing for seamless integration into existing ecosystems.
Interoperability at its Core
With 100% interoperability with Java, BoxLang seamlessly bridges the gap between traditional and modern development paradigms, unlocking new possibilities for innovation and collaboration.
Multi-Runtime
From the tiny 2m operating system binary to running on our pure Java web server, CommandBox, Jakarta EE, AWS Lambda, Microsoft Functions, Web Assembly, Android and more. BoxLang has been designed to enhance and adapt according to it's runnable runtime.
The Fusion of Modernity and Tradition
Experience the fusion of modern features inspired by CFML, Node, Ruby, Kotlin, Java, and Clojure, combined with the familiarity of Java bytecode compilation, making BoxLang a language of choice for forward-thinking developers.
Empowering Transition with Transpiler Support
Transitioning from CFML to BoxLang is seamless with our JIT transpiler, facilitating smooth migration and preserving existing code investments.
Unlocking Creativity with IDE Tools
Unleash your creativity with powerful IDE tools tailored for BoxLang, providing an intuitive development experience and streamlining your workflow. Join us as we embark on a journey to redefine JVM development. Welcome to the era of BoxLang.
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...Jason Yip
The typical problem in product engineering is not bad strategy, so much as “no strategy”. This leads to confusion, lack of motivation, and incoherent action. The next time you look for a strategy and find an empty space, instead of waiting for it to be filled, I will show you how to fill it in yourself. If you’re wrong, it forces a correction. If you’re right, it helps create focus. I’ll share how I’ve approached this in the past, both what works and lessons for what didn’t work so well.
The Department of Veteran Affairs (VA) invited Taylor Paschal, Knowledge & Information Management Consultant at Enterprise Knowledge, to speak at a Knowledge Management Lunch and Learn hosted on June 12, 2024. All Office of Administration staff were invited to attend and received professional development credit for participating in the voluntary event.
The objectives of the Lunch and Learn presentation were to:
- Review what KM ‘is’ and ‘isn’t’
- Understand the value of KM and the benefits of engaging
- Define and reflect on your “what’s in it for me?”
- Share actionable ways you can participate in Knowledge - - Capture & Transfer
"NATO Hackathon Winner: AI-Powered Drug Search", Taras KlobaFwdays
This is a session that details how PostgreSQL's features and Azure AI Services can be effectively used to significantly enhance the search functionality in any application.
In this session, we'll share insights on how we used PostgreSQL to facilitate precise searches across multiple fields in our mobile application. The techniques include using LIKE and ILIKE operators and integrating a trigram-based search to handle potential misspellings, thereby increasing the search accuracy.
We'll also discuss how the azure_ai extension on PostgreSQL databases in Azure and Azure AI Services were utilized to create vectors from user input, a feature beneficial when users wish to find specific items based on text prompts. While our application's case study involves a drug search, the techniques and principles shared in this session can be adapted to improve search functionality in a wide range of applications. Join us to learn how PostgreSQL and Azure AI can be harnessed to enhance your application's search capability.
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Keywords: AI, Containeres, Kubernetes, Cloud Native
Event Link: https://meine.doag.org/events/cloudland/2024/agenda/#agendaId.4211
From Natural Language to Structured Solr Queries using LLMsSease
This talk draws on experimentation to enable AI applications with Solr. One important use case is to use AI for better accessibility and discoverability of the data: while User eXperience techniques, lexical search improvements, and data harmonization can take organizations to a good level of accessibility, a structural (or “cognitive” gap) remains between the data user needs and the data producer constraints.
That is where AI – and most importantly, Natural Language Processing and Large Language Model techniques – could make a difference. This natural language, conversational engine could facilitate access and usage of the data leveraging the semantics of any data source.
The objective of the presentation is to propose a technical approach and a way forward to achieve this goal.
The key concept is to enable users to express their search queries in natural language, which the LLM then enriches, interprets, and translates into structured queries based on the Solr index’s metadata.
This approach leverages the LLM’s ability to understand the nuances of natural language and the structure of documents within Apache Solr.
The LLM acts as an intermediary agent, offering a transparent experience to users automatically and potentially uncovering relevant documents that conventional search methods might overlook. The presentation will include the results of this experimental work, lessons learned, best practices, and the scope of future work that should improve the approach and make it production-ready.
Essentials of Automations: Exploring Attributes & Automation ParametersSafe Software
Building automations in FME Flow can save time, money, and help businesses scale by eliminating data silos and providing data to stakeholders in real-time. One essential component to orchestrating complex automations is the use of attributes & automation parameters (both formerly known as “keys”). In fact, it’s unlikely you’ll ever build an Automation without using these components, but what exactly are they?
Attributes & automation parameters enable the automation author to pass data values from one automation component to the next. During this webinar, our FME Flow Specialists will cover leveraging the three types of these output attributes & parameters in FME Flow: Event, Custom, and Automation. As a bonus, they’ll also be making use of the Split-Merge Block functionality.
You’ll leave this webinar with a better understanding of how to maximize the potential of automations by making use of attributes & automation parameters, with the ultimate goal of setting your enterprise integration workflows up on autopilot.
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving
What began over 115 years ago as a supplier of precision gauges to the automotive industry has evolved into being an industry leader in the manufacture of product branding, automotive cockpit trim and decorative appliance trim. Value-added services include in-house Design, Engineering, Program Management, Test Lab and Tool Shops.
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsDianaGray10
Join us to learn how UiPath Apps can directly and easily interact with prebuilt connectors via Integration Service--including Salesforce, ServiceNow, Open GenAI, and more.
The best part is you can achieve this without building a custom workflow! Say goodbye to the hassle of using separate automations to call APIs. By seamlessly integrating within App Studio, you can now easily streamline your workflow, while gaining direct access to our Connector Catalog of popular applications.
We’ll discuss and demo the benefits of UiPath Apps and connectors including:
Creating a compelling user experience for any software, without the limitations of APIs.
Accelerating the app creation process, saving time and effort
Enjoying high-performance CRUD (create, read, update, delete) operations, for
seamless data management.
Speakers:
Russell Alfeche, Technology Leader, RPA at qBotic and UiPath MVP
Charlie Greenberg, host
Discover the Unseen: Tailored Recommendation of Unwatched ContentScyllaDB
The session shares how JioCinema approaches ""watch discounting."" This capability ensures that if a user watched a certain amount of a show/movie, the platform no longer recommends that particular content to the user. Flawless operation of this feature promotes the discover of new content, improving the overall user experience.
JioCinema is an Indian over-the-top media streaming service owned by Viacom18.
AppSec PNW: Android and iOS Application Security with MobSFAjin Abraham
Mobile Security Framework - MobSF is a free and open source automated mobile application security testing environment designed to help security engineers, researchers, developers, and penetration testers to identify security vulnerabilities, malicious behaviours and privacy concerns in mobile applications using static and dynamic analysis. It supports all the popular mobile application binaries and source code formats built for Android and iOS devices. In addition to automated security assessment, it also offers an interactive testing environment to build and execute scenario based test/fuzz cases against the application.
This talk covers:
Using MobSF for static analysis of mobile applications.
Interactive dynamic security assessment of Android and iOS applications.
Solving Mobile app CTF challenges.
Reverse engineering and runtime analysis of Mobile malware.
How to shift left and integrate MobSF/mobsfscan SAST and DAST in your build pipeline.
The Microsoft 365 Migration Tutorial For Beginner.pptxoperationspcvita
This presentation will help you understand the power of Microsoft 365. However, we have mentioned every productivity app included in Office 365. Additionally, we have suggested the migration situation related to Office 365 and how we can help you.
You can also read: https://www.systoolsgroup.com/updates/office-365-tenant-to-tenant-migration-step-by-step-complete-guide/
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...GlobalLogic Ukraine
Під час доповіді відповімо на питання, навіщо потрібно підвищувати продуктивність аплікації і які є найефективніші способи для цього. А також поговоримо про те, що таке кеш, які його види бувають та, основне — як знайти performance bottleneck?
Відео та деталі заходу: https://bit.ly/45tILxj
Session 1 - Intro to Robotic Process Automation.pdfUiPathCommunity
👉 Check out our full 'Africa Series - Automation Student Developers (EN)' page to register for the full program:
https://bit.ly/Automation_Student_Kickstart
In this session, we shall introduce you to the world of automation, the UiPath Platform, and guide you on how to install and setup UiPath Studio on your Windows PC.
📕 Detailed agenda:
What is RPA? Benefits of RPA?
RPA Applications
The UiPath End-to-End Automation Platform
UiPath Studio CE Installation and Setup
💻 Extra training through UiPath Academy:
Introduction to Automation
UiPath Business Automation Platform
Explore automation development with UiPath Studio
👉 Register here for our upcoming Session 2 on June 20: Introduction to UiPath Studio Fundamentals: https://community.uipath.com/events/details/uipath-lagos-presents-session-2-introduction-to-uipath-studio-fundamentals/
What is an RPA CoE? Session 1 – CoE VisionDianaGray10
In the first session, we will review the organization's vision and how this has an impact on the COE Structure.
Topics covered:
• The role of a steering committee
• How do the organization’s priorities determine CoE Structure?
Speaker:
Chris Bolin, Senior Intelligent Automation Architect Anika Systems
2. 2
2
●
Collections – Part IV
– Object-based vs. generic Collections
●
Generics Types in Java
– Sequential and associative Collections
– Associative Collections
●
Equivalence-based associative Collections: .Net's SortedDictionary
●
Operations on .Net's IDictionarys
●
Comparison and Implementation of .Net's Interfaces IComparable and IComparer
TOC
3. 3
3
●
Explicitly typed – i.e. typenames must be explicitly written at their declaration:
●
Safely typed – i.e. unrelated types can't fool the compiler.
– Cross casting and other pointer stuff is generally illegal.
●
Statically typed – i.e. variables' types are determined at compile time:
●
Sorry? But the same variable can hold different sub type objects at run time!
– Indeed! We can define variables that may hold e.g. any derived type:
– .Net differs the static (Object) and the dynamic type (Car) of an instance.
– The idea of static/dynamic types is used for run time polymorphism in .Net.
double sum = 5.2; // Type name "double" must be explicitly written for the variable sum.
int count = 42; // count is of type int, we can only perform int operations on it!
Object o = new Car(); // Type Car is derived from type Object.
The Type System in .Net 1 (presented in C#1) – Part I
4. 4
4
●
Esp. object-based collections rely on the cosmic hierarchy of .Net's type system: everything is an Object:
– .Net 1 collections: Hold items of static type Object, their dynamic types can vary.
●
In fact collections must be able to hold any type in order to be versatile.
– .Net 1 "resorted" to run time polymorphism (i.e. Liskov Substitution Principle (LSP)) to get this versatility.
– So in a .Net 1 collection, objects of any dynamic type can be stored.
●
Object-based collections work great, as long as...
– we'll only store objects of dynamic types that dependent code awaits,
– we'll only cast down to dynamic types that dependent code put in,
– we'll never put mixed unrelated dynamic types into the same collection,
– well as we don't fall into a type problem during run time.
ArrayList lines = new ArrayList(File.ReadAllLines("/Library/Logs/Software Update.log")); // File.ReadAllLines() was introduced with .Net 2!
object item1 = lines[0];
object item2 = lines[1];
// We have to use cast contact lenses to get the dynamic types out of the objects:
string text1 = (string)item1;
// Access string's interface:
int result = text1.IndexOf('g');
// We can also cast directly from the index notation:
string text2 = (string)lines[1];
The Type System in .Net 1 (presented in C#1) – Part II
5. 5
5
●
The problem or lack in the type system using LSP can be presented with the just created collectionlines:
●
The problem is that we as programmers have to know about the contained dynamic types (strings and not Cars in lines).
– Whenever Object is used in an interface (the return value of lines' indexer), some convention must be around.
– This convention describes the dynamic type, we're really dealing with (strings and not Cars).
– The contributed programers have just to obey the convention... ;-)
●
We as programmers have to cast down (or unbox) to the type we await.
– The cast is needed to access the interface of a static type (e.g. car.StartEngine()).
– These casts indicate that the programer knows more than the compiler!
– The compiler wears "cast contact lenses"; it can't type check, it trusts the programmer!
– These casts are type checked at run time, so they are consuming run time!
– Type errors (an item of lines was casted to Car instead of string) will happen at run time, not at compile time.
object item1 = lines[0];
// But, these are not the awaited types, we can't deal with Cars, we await strings!
// This cast will fail! An InvalidCastException will be thrown!
Car car = (Car)item1;
car.StartEngine();
public class Car {
public void StartEngine() {
/* pass */
}
}
The Type System in .Net 1 (presented in C#1) – Part III
6. 6
6
●
Object-based collections have an interesting feature: we can beheterogeneous collections:
– In a heterogeneous collection every item can have any different dynamic type:
●
It works, but heterogeneous collections are tricky: developers need to know, on which indexes objects of certain types
reside.
●
Heterogenous collection should be avoided! Strive to using homogenous collections or other solutions!
ArrayList objects = new ArrayList();
// Since each item is of type object, we can add any object to an ArrayList:
objects.Add("aString"); // String
objects.Add(42); // int
objects.Add(new object()); // object
objects.Add(new [] {1, 2, 3, 4}); // int[]
foreach(object item in objects) {
Console.WriteLine(item);
}
// This statement will fail, we can't deal with string, on index 1 an int was stored!
// An InvalidCastException will be thrown!
string result = (string)objects[1];
Homogeneous and heterogeneous Collections
7. 7
7
●
What could we do close the lack in the .Net 1 type system to stay typesafe?
●
We could use strictly typed arrays as collections if possible, they're not object-based and therefore typesafe:
– However, arrays can not be used, when the collection in question needs to be modified (enlarged or downsized) after creation.
●
We could create own, typesafe not object-based collections as UDTs (e.g. a special string-list for the discussed example).
– In .Net we could resort to so called specialized collections in the namespace System.Collections.Specialized, e.g. StringCollection.
●
But in the world of collections, there is a much better way to work in a typesafe manner: generic collections!
// Create an array that hold strings:
string[] lines = File.ReadAllLines("/Library/Logs/Software Update.log"));
// With arrays we don't need casts, instead we can directly access lines' items as string objects:
string text1 = lines[0];
// Access string's interface:
int result = text1.IndexOf('g');
// Create a specialized StringCollection:
StringCollection lines = new StringCollection();
lines.AddRange(File.ReadAllLines("/Library/Logs/Software Update.log"));
// With the specialized StringCollection we don't need casts, instead we can directly access lines' items as string objects:
string text1 = lines[0];
// Access string's interface:
int result = text1.IndexOf('g');
The Type System in .Net 1 – Some Remedy
8. 8
8
●
Let's improve our problematic code with the generic collection List<T>:
●
.Net 2 introduced generic types to get rid of the presented type problems.
– Generic types are types that leave a part of their type information open.
– Generics are an outstanding feature in .Net 2.
●
Generics (here List<T>) leave type information open? How should this help me out?
– The open type information is accessible by type parameters (here T).
– As programmers we can fill the type parameters by concrete type arguments (here string).
– By setting type arguments of a generic type we create another type, the constructed type (List<string> in this case).
●
The full name of the constructed type is List<string>!
– => Net effect: The type argument (string) will be of static type, so the formerly open type information can be checked by the compiler.
– In the end typesafety means that types are checked by the compiler at compile time and no longer at run time.
// Create a generic List that holds strings:
List<string> lines = new List<string>(File.ReadAllLines("/Library/Logs/Software Update.log"));
// This time we don't need casts, instead we can directly access lines' items as string objects:
string text1 = lines[0];
// Access string's interface:
int result = text1.IndexOf('g');
// The generic type List<T>:
public class List<T> { // (members hidden)
public void Add(T item) {
/* pass */
}
}
// This time we'll get a compile time error:
Car car1 = lines[1];
// The type argument in lines was string, not Car!
// Cannot convert string to Car.
car1.StartEngine();
Generics to the Rescue
9. 9
9
●
.Net's generic collections live in the namespace System.Collections.Generic.
●
The generic counterpart of the collection ArrayList is List<T>, T is the type parameter.
– List<T>'s interface is set to the open type T in parameter- and return-types of methods.
– The type parameter T acts as a placeholder for the actual type argument.
●
When a type is constructed, T is replaced by a type argument (the result is the constructed type).
– List<string>'s interface is set to the static type string in parameter- and return- types of methods.
●
The idea of generics is to use types (i.e. not values) as arguments!
– The typesafty we got is that generics move type run time errors to compile time errors.
// The generic type List<T>:
public class List<T> { // (details hidden)
public void Add(T item) { /* pass */ }
public List<T> GetRange(int index, int count) { /* pass */ }
}
// The constructed type List<string> has following interface:
public class List<string> { // (details hidden)
public void Add(string item) { /* pass */ }
public List<string> GetRange(int index, int count) { /* pass */ }
}
// Create a generic List that holds strings:
List<string> lines;
List
T
The UML represents generic
types as parameterized classes.
Generics – Overview
List<T -> string>
«bind»
<T -> string>
List<string>
implicit binding against a type
argument
explicit binding against a type
argument
10. 10
10
●
It is also possible to define generic types, whose type argument is another generic type.
– E.g. we can define a list of lists, i.e. a collection of collections, which is effectively a two-dimensional array or matrix.
– Such collections are better than multidimensional arrays in some aspects:
●
They offer the same concept to express rectangular as well as jagged arrays.
●
"Real" collections are very flexible, as elements can be added and removed (or: the matrix' dimensions can be enlarged and shrank).
●
The .Net framework as well as Java do also support generic types having two or more type parameters:
– E.g. with the type SortedDictionary<TKey, Tvalue> (this type will be discussed later):
●
To understand collections in Java, C++ and .Net it is required to understand alsoadvanced generics.
// Creating a SortedDictionary object:
SortedDictionary<string, int> aDictionary = new SortedDictionary<string, int>();
aDictionary.Add("fortytwo", 42);
// The generic type SortedDictionary<TKey, TValue>:
public class SortedDictionary<TKey, TValue> { // (members hidden)
/* pass */
}
// A jagged array in C# as matrix:
int[][] matrix = new int[3][];
matrix[0] = new[] {1, 2, 3, 4};
matrix[1] = new[] {6, 7};
matrix[2] = new[] {8, 9, 0};
Console.WriteLine("Item: {0}", matrix[1][0]);
// >Item: 6
// A list of lists of int as matrix:
List<List<int>> matrix = new List<List<int>>();
matrix.Add(new List<int>{1, 2, 3, 4});
matrix.Add(new List<int>{6, 7});
matrix.Add(new List<int>{8, 9, 0});
Console.WriteLine("Item: {0}", matrix[1][0]);
// >Item: 6
Slightly advanced Generics
11. 11
11
●
Hence, we'll use generic types whenever appropriate. We'll define following substitutes for already introduced collections:
– ICollection → ICollection<T>
– IList → IList<T>
– ArrayList → List<T>
– IEnumerable → IEnumerable<T>
– IEnumerator → IEnumerator<T>
– .Net's framework design guidelines suggest using only generic collection types in public interfaces.
●
From object-based to generic collections:
IList names = new ArrayList();
names.Add("James");
names.Add("Miranda");
// Get the values back (object-based collection: static type Object):
object name1 = names[0]; // "James"
object name2 = names[1]; // "Miranda"
string name1AsString = (string)name1; // Cast the string out of the object.
string name2As = (string)names[1]; // Cast directly from the index notation.
names[1] = "Meredith";
Console.WriteLine(names[1]);
// >Meredith
IList<string> names = new List<string>();
names.Add("James");
names.Add("Miranda");
// Get the values back (generic string-collection: static type string):
string name1 = names[0]; // "James"
string name2 = names[1]; // "Miranda"
names[1] = "Meredith";
Console.WriteLine(names[1]);
// >Meredith
The better Type System –
from object-based to generic Collections
12. 12
12
●
C++ templates are, at least principally, C++' equivalent to .Net's and Java's generics.
– C++ provides the template std::vector<T> (<vector>), which is functionally equivalent to .Net's List<T>:
– Before C++ had templates, void*-based collections have been used, incl. cast contact lenses. - This is still true for C.
●
void*-based collections are the functional equivalent to object-based collections!
●
Objective-C and many scripting languages use so calleddynamic typing instead of generic or object-based structures.
– (We're not going to discuss these concepts in this course.)
// names is a vector containing string-elements.
std::vector<std::string> names;
names.push_back("James");
names.push_back("Miranda");
// Get the values back (template string-container: static type std::string):
std::string name1 = names[0]; // "James"
std::string name2 = names[1]; // "Miranda"
names[1] = "Meredith";
std::cout<<names[1]<<std::endl;
// >Meredith
// in h-file <vector>
template <typename T> class vector { // (details hidden)
public:
void push_back(const T& newItem);
};
The Collection Type System of the C++ STL
13. 13
13
●
The story about generic collections in Java is somewhat advanced,but Java programmers should know these facts.
– A good way to understand Java's generics (and the problems that come with it) is to compare them to, e.g., .Net's generics.
●
Here we have basically the same generic class in Java and C#:
– The definition of instances of these classes has almost the same syntax in Java and C#:
●
In Java we can only use reference types as type arguments for generic types. E.g. we can not create MyList<int> or MyList<double>.
– As we know the idea behind generics is to have typesafty. So the last statements won't compile respectively:
The Collection Type System on the Java Platform – Part I
// Java
public class MyList<T> {
public List<T> items = new ArrayList<T>(5);
}
// Java
stringList.items.add("Frank"); // OK for the compiler! A string literal can be set, because items is a List<String>.
stringList.items.add(42); // Invalid for the compiler! Generics are typesafe! An int literal can't be set, because items is not a List<Integer>.
MyList<String> stringList = new MyList<String>();
MyList<Integer> intList = new MyList<Integer>();
MyList<string> stringList = new MyList<string>();
MyList<int> intList = new MyList<int>();
// C#
public class MyList<T> {
public IList<T> items = new List<T>(5);
}
// C#
stringList.items.Add("Frank"); // OK for the compiler! See explanation for Java above.
stringList.items.Add(42); // Invalid for the compiler! See explanation for Java above.
14. 14
14
●
The difference between Java and .Net is that different things are generated at compile time.
– A compiler creating .Net IL code will produce a so called constructed type for each "filled out" generic type in the code:
– A compiler creating Java bytecode will just erase the type argument and will fall back to an object-based type:
●
This compilation step is called type erasure. The resulting type (w/o generic type parameters) is called the raw type of the generic type.
●
Often this isn't a problem in Java, because compile time typesafety is fine, but it hurts the run time typesafety!
●
Ouch! But Java provides a means to reestablish run time typesafety: run time type checked collection wrappers.
The Collection Type System on the Java Platform – Part II
stringList.items.add("Frank"); // Ok as before!
((MyList)stringList).items.add(42); // Huh? Casting (cast contact lenses) to the raw type and adding an int: ok for compiler and at run time!
String itemAt1 = stringList.items.get(1); // Bang! Getting the int at the index one via the generic type: ok for the compiler but crashes at run time!
// java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
type construction of a .Net IL compiler
// Java
MyList<String> stringList = new MyList<String>();
MyList<Integer> intList = new MyList<Integer>();
public class MyList { // Raw type
public List items = new ArrayList(5);
}
type erasure of a Java bytecode compiler
// C#
MyList<string> stringList = new MyList<string>();
MyList<int> intList = new MyList<int>();
public class MyList<string> { // Constructed type
public IList<string> items = new List<string>(5);
}
public class MyList<int> { // Constructed type
public IList<int> items = new List<int>(5);
}
15. 15
15
●
Java provides the class Collections with some static methods (simple factories) to create run time type checked collections.
– A present collection needs to be passed to Collections.checked...() and a new collection wrapping the passed one will be returned.
– Let's wrap MyList's encapsulated List to be a checked List with Collections.checkedList():
●
More simple factories can be found in the class Collections as static methods (checkedSet(), checkedMap() etc.).
– The return type of all of these simple factories are just interface types, the type checked implementations are always hidden.
– So the UML diagram of the relations between the contributing types looks like so:
●
Run time type checked wrappers were added to the JDK in order have compatibility w/ non-generic collections, retaining
compile time typesafty of generics and having run time typesafety.
– There is an initiative in the Java community to introduce generic types with constructed types into Java: reified generics.
– Mind that run time type checking is costly!
The Collection Type System on the Java Platform – Part III
stringList.items = Collections.checkedList(stringList.items, String.class); // Wrap items, so that it can only deal with strings at compile time.
stringList.items.add("Frank"); // Ok as before! It was already checked by the compiler.
((MyList)stringList).items.add(42); // Bang! An int can't be added to a list that is only allowed to contain Strings!
String itemAt1 = stringList.items.get(1); // Will not be reached at all!
<<interface>>
List
HiddenCheckedListImplementation
exposes implements
Collections
+ checkedList(list : List<T>, type : Class<T>) : List<T>
instantiates
T
16. 16
16
●
Up to now, we discussed relatively simple indexed and sequential collections.
●
Besides indexed and sequential collections there also exist so calledassociative collections.
●
In opposite to indexed and sequential collections,associative collections inspect the stored objects.
– E.g. the indexed collection ArrayList just stores references to objects, but it does never, e.g., call methods on these objects.
●
For indexed and sequential collections the contained items are said to be transparent.
– Associative collections have to inspect stored objects for equivalence or equality in order to provide very mighty features.
●
Let's start by analyzing a problem, which can be solved with associative collections.
Indexed, sequential and associative Collections
17. 17
17
●
Let's assume that we have to handle color names and figure out the belonging to HTML color codes:
●
Of course the task can be solved this way, but the solution is based on a possiblyfragile assumption:
– The two separate arrays need to hold belonging to values at the same indexes!
– Basically we've to go through all items sequentially and compare (Array.IndexOf()).
– We say the association is index-based.
●
The presented algorithm is a so called lookup-algorithm (lookup).
– Lookups are used very often in programming.
– A problem of lookups is that separate collections (colorNames and htmlColorCode) need to be evaluated (like tables in relational databases).
– Modern collection frameworks provide dedicated collections to cover lookups in a comfortable manner: associative collections.
// C#
// Here we have two arrays that hold color names and HTML color codes:
string[] colorNames = {"Blue", "Red", "Green"} ;
int[] htmlColorCodes = {0x0000FF, 0xFF0000, 0x00FF00};
// With the information given, the task to pick an HTML color code from a color name is trivial: Because the
// index of the color name matches the index of the color HTML code, we can formulate a simple algorithm:
int indexOfRed = Array.IndexOf(colorNames, "Red");
int colorCodeOfRed = htmlColorCodes[indexOfRed];
Console.WriteLine("Color code for Red: {0:X6}", colorCodeOfRed);
// >Color code for Red: FF0000
colorNames0x0000FF 0xFF0000 0x00FF00
"Blue" "Red" "Green" htmlColorCodes
210 matching indexes
Example – Color Names to HTML Color Codes – Part I
18. 18
18
colorNamesToColorCodes
●
Associative collections abstract the usage of multiple collections to solve the just presented lookupin an intuitive manner:
– Here .Net's associative collection SortedDictionary<string, int> is shown (it implements IDictionary<string, int>):
– The association of both, color names and color codes, is available via the single collection colorNamesToHtmlColorCodes.
●
We have to rethink our termination: associative collections associate a key (color name) to a value (color code).
– The association is key-based and no longer index-based.
– The internal "organization" is key-value-pair-based.
– In a sense an array is nothing but an associative collection that associates a value with an index (mind the []-syntax).
– In fact real problems often involve associating values with other values, e.g.: White pages, thesaurus, document index.
●
The .Net collection KeyedCollection<K, T> allows the lookup of data stored in the value (i.e. there are no key-value-pairs).
// Associating color names with HTML color codes using a SortedDictionary:
IDictionary<string, int> colorNamesToColorCodes = new SortedDictionary<string, int>();
colorNamesToColorCodes.Add("Blue", 0x0000FF);
colorNamesToColorCodes.Add("Red", 0xFF0000);
colorNamesToColorCodes.Add("Green", 0x00FF00);
int colorCodeOfRed = colorNamesToColorCodes["Red"];
Console.WriteLine("Color code for Red: {0:X6}", colorCodeOfRed);
// >Color code for Red: FF0000
0x0000FF 0xFF0000 0x00FF00
"Blue" "Red" "Green"
Key-value-pair
{"Green", 0x00FF00}
Example – Color Names to HTML Color Codes – Part II
● Mind how the term key (primary/foreign key) is also
applied in the design of databases.
● Indeed KeyedCollection is a very useful collection.
However, it is not a classical associative collection,
because it uses linear search (it is backed by a List
and calls Contains() on that List potentially for each
item). The abstract class KeyedCollection needs to
be specialized (overriding GetKeyForItem(), i.e. we
have the template method design pattern here) to
get the key from the managed item/value.
19. 19
19
●
In many scripting languages associative collections havespecial syntactical support.
– The names "hash", "hashmap" or "associative array" are common in scripting languages.
– In JavaScript every object is a collection of property-value-pairs per se. An array is also an associative collection:
●
In other platforms associative collections are often called Maps (Java) or Dictionaries (Cocoa, .Net).
– Esp. the term "Map" is taken from the phrase "to map something", which means "to associate something".
– The term "hash" still needs to be clarified in this context: we have to understand how associative collections work.
●
We'll start discussing equivalence-based associative collections and then equality-based associative collections using hashing.
# E.g. in Ruby associative collections are supported as "hashes" with integrated syntactical support.
# Just initialize a variable with a list of key => value pairs:
colorNamesToColorCodes = {"Blue" => 0x0000FF, "Red" => 0xFF0000, "Green" => 0x00FF00}
# The items can be accessed with the []-operator:
printf("Color code for Red: %06X", colorNamesToColorCodes["Red"])
# >Color code for Red: FF0000
// JavaScript
// Create associative collection as object with properties:
var colorNamesToColorCodes = new Object();
colorNamesToColorCodes.Blue = 0x0000FF;
colorNamesToColorCodes.Red = 0xFF0000;
colorNamesToColorCodes.Green = 0x00FF00;
console.log("Color code for Red: "
+colorNamesToColorCodes.Red.toString(16));
// >Color code for Red: FF0000
// JavaScript
// Create associative collection as associative array:
var colorNamesToColorCodes = new Object();
colorNamesToColorCodes["Blue"] = 0x0000FF;
colorNamesToColorCodes["Red"]= 0xFF0000;
colorNamesToColorCodes["Green"]= 0x00FF00;
console.log("Color code for Red: "
+colorNamesToColorCodes["Red"].toString(16));
// >Color code for Red: FF0000
Associative Collections in other Languages
20. 20
20
●
New about associative collections is that associative collections inspect the items they hold.
– I.e. associative collections operate on contained items: they call methods on the keys of the contained key-value-pairs.
– Associative collections need to compare the keys they hold.
– In opposite to other collections, items are got and set by analyzing their relationships.
●
Associative collections are very powerful and allow writing elegant/readable algorithms to solve complicated problems.
– Associative collections could be implemented with two arrays as shown before, but this would be inefficient for common cases.
– A clever internal organization of associative collections is required to allow efficient access and modification of contained items.
●
There are two general ways to organize items (i.e. their keys) in an associative collection:
– (1) By equivalence. I.e. by their relative order/order-relationship, such as less than and greater than.
– (2) By equality. I.e. by hash-codes and the result of the equality check (methods hashCode()/equals() (Java) or
GetHashCode()/Equals() (.Net)).
●
In this and the next lecture we're going to discuss associative collections that organize their keys byequivalence.
– This is the case for SortedDictionary, so we'll discuss .Net's SortedDictionary.
Organization of Items in associative Collections
● It should be mentioned that some methods of list-
types already needed to inspect the contained items
to function, e.g. Contains(), Remove(), IndexOf().
These methods use equality to inspect/compare
values.
21. 21
21
●
Create the empty SortedDictionary<K, V> colorNamesToColorCodes:
●
Then we can add three key-value-pairs like so:
●
Get the value of a key, i.e. make a lookup with the indexer ([]-operator):
●
Check, whether an entry with a certain key is already existing with the method ContainsKey():
●
Iteration: The internal organization is key-value-pair-based, so IDictionary's iterator produces an iterator of key-value pairs.
C# – collection initializers for dictionaries
// Apply a collection initializer on a SortedDictionary:
IDictionary<string, int> colorNamesToColorCodes2 = new SortedDictionary<string, int> {
{"Blue", 0x0000FF}, {"Red", 0xFF0000}, {"Green", 0x00FF00}
};
IDictionary<string, int> colorNamesToColorCodes = new SortedDictionary<string, int>();
colorNamesToColorCodes.Add("Blue", 0x0000FF);
colorNamesToColorCodes.Add("Red", 0xFF0000);
colorNamesToColorCodes.Add("Green", 0x00FF00);
int valueForBlue = colorNamesToColorCodes2["Blue"];
// >0x0000FF
Operations on IDictionarys – Part I
// IDictionary<string, int> implements IEnumerable<KeyValuePair<string, int>>.
// Iteration yields KeyValuePair<string, int>-items:
foreach (KeyValuePair<string, int> item in colorNamesToColorCodes) {
Console.WriteLine(item);
}
bool blueAlreadyPresent = colorNamesToColorCodes2.ContainsKey("Blue");
// >true
● Because colorNamesToColorCodes is virtually a
SortedDictionary, the iteration will yield the items in
the order sorted by their keys.
22. 22
22
●
Trying to query the value for a key that doesn't exist will throw a KeyNotFoundException:
– To avoid these "surprises" check the key for existence (with ContainsKey()), before it is looked up.
●
Adding a pair for an already existing key will throw an ArgumentException.
– .Net dictionaries don't allow having a key with multiple values. (However, the C++' STL-container std::multimap can handle this.)
●
The indexer allows adding new entries as well as replacing values of existing key-value-pairsand reading values:
●
We can get the current count of elements stored in the dictionary (Count is required by implementing ICollection<T>):
colorNamesToColorCodes.Add("Blue", 17); // Throws ArgumentException: a key-value-pair with the same key already exists in the dictionary.
colorNamesToColorCodes["Blue"] = 17; // OK! Replaces "Blue"'s value 0x0000FF with 17.
colorNamesToColorCodes["Yellow"] = 0xFFFF00; // Adds the new key-value-pair {"Yellow", 0xFFFF00}.
if (colorNamesToColorCodes.ContainsKey("Yellow")) { // Checking the existence of the key "Yellow".
// Use the indexer to retrieve "Yellow"'s value:
Console.WriteLine("Color code for Yellow: {0:X6}", colorNamesToColorCodes["Yellow"]);
// >Color code for Yellow: FFFF00
}
Console.WriteLine(colorNamesToColorCodes.Count);
// >4
Operations on IDictionarys – Part II
int valueForOrange = colorNamesToColorCodes2["Orange"]; // Throws KeyNotFoundException: a key-value-pair with that key doesn't exists in the dictionary.
23. 23
23
●
Now its time to understand how SortedDictionarys work basically, we'll discuss it in depth in the next lecture.
– We have to clarify, how SortedDictionary knows if a key is already present or not! - It needs to compare keys somehow!
●
The question is: "How does SortedDictionary know if two keys are equal?"
– A part of the answer is that SortedDictionary doesn't know, if two items are equal, but it knows if two items are equivalent!
– SortedDictionary's comparison is based on the order-relationship among items. This is called equivalence comparison.
●
The order-relationship can be expressed by evaluating two values one beingless than, greater than or equal the other.
– If of two values one is neither less than nor greater than the other the values are said to be equivalent (Not equal!).
– .Net provides a way for types to declare equivalence comparability: implementing the interface IComparable/IComparable<T>.
– (The C++ STL requires types to override operator< to implement equivalence comparability.)
●
Now we are going to understand how IComparable/IComparable<T> has to be implemented for own UDTs.
SortedDictionary and Equivalence Comparison
24. 24
24
UDTs as Keys of associative Collections – Part I
● Up to now we've only used objects of builtin types for the keys of associative collections (e.g. string).
– Now we are going to explore how to use keys of our own types. Let's do this with the UDT Car:
– Obviously it doesn't work this way! - What did we miss?
● The problem is that nobody (esp. SortedDictionary) knows, how to compare Cars!
– One way to implement this: Car could itself know, how it can be compared – we've to implement IComparable<Car> in Car:
– IComparable<T>.CompareTo() should return a value less than 0, if this < other, a value greater than 0, if this > other and otherwise 0.
●
For Car we'll delegate the implementation of
IComparable<Car>.CompareTo() to Car's property
Name, Name is of type string (string implements
IComparable<string>).
– With this implementation of Car
SortedDictionary<TKey, TValue> works
as expected:
public class Car {
public string Name {get; set;}
}
IDictionary<Car, string> carToManufacturer = new SortedDictionary<Car, string>();
// Adding the first item won't require to compare items:
carToManufacturer[new Car{ Name = "Focus" }] = "Ford";
// Will throw ArgumentException: Object doesn't implement IComparable!
carToManufacturer[new Car{ Name = "Auris" }] = "Toyota";
IDictionary<Car, string> carToManufacturer = new SortedDictionary<Car, string>();
carToManufacturer[new Car{ Name = "Focus" }] = "Ford";
// OK!
carToManufacturer[new Car{ Name = "Auris" }] = "Toyota";
public class Car : IComparable<Car> { // (members hidden)
public int CompareTo(Car other) {
// Very simple implementation that compares the Cars' Name fields:
return this.Name.CompareTo(other.Name);
}
}
● The associative collection does really look into the
items: just set a breakpoint into the Car.
CompareTo() method!
25. 25
25
UDTs as Keys of associative Collections – Part II
● But there are cases, in which implementing IComparable<T> is no option to make types usable as keys:
– (1) if we can not modify the type in question, e.g. if it is a type of a 3rd
party library,
– (2) if the type in question does already implement IComparable<T>, but the implemented comparison doesn't meet our needs,
– (3) if the type doesn't implement IComparable<T> at all.
● Let's assume that we want to use Cars as keys by case insensitive comparison of their Name property.
– We could change the implementation of Car.CompareTo(), but this would hurt the Open-Close Principle (OCP).
– Effectively we have the case (2). The present implementation of IComparable<Car> doesn't meet our needs.
● To cover these cases there is another way to implement comparison:implement comparison in a different type (not in Car).
– I.e. we can implement a dedicated type that has only one responsibility: comparing Cars. Such a type is called comparator.
– The .Net framework provides a special interface to support such special comparison types: IComparer/IComparer<T>.
– Now it's time to implement a comparer to compare the case insensitive Name of Cars.
● If a type does not implement IComparable<T>, and
we try to add at least two instances of that type used
as key into a SortedDictionary, an
ArgumentException will be thrown.
26. 26
26
UDTs as Keys of associative Collections – Part III
● The type SortedDictionary<TKey, TValue> accepts an object of type IComparer<TKey> in one of its ctors:
– As can be seen the passed comparer refers to the type TKey.
● The comparer to specify in the ctor determines, how Cars are getting compared. The comparer looks like this:
● Here we'll finally pass an instance of the created CaseInsensitveCarComparer to SortedDictionary's ctor:
public class CaseInsensitiveCarComparer : IComparer<Car> {
public int Compare(Car lhs, Car rhs) {
// Very simple implementation that compares the Name
// fields of two Cars ignoring the case:
return string.Compare(lhs.Name, rhs.Name, true);
}
}
// The generic type SortedDictionary<TKey, TValue>:
public class SortedDictionary<TKey, TValue> { // (details hidden)
public SortedDictionary(IComparer<TKey> comparer);
}
// Create a dictionary and specify the special comparer in the ctor:
IDictionary<Car, string> carToManufacturer = new SortedDictionary<Car, string>(new CaseInsensitiveCarComparer());
carToManufacturer[new Car{ Name = "Cortina" }] = "Ford";
// This won't add another "cortina", because the specified comparer evaluates "Cortina" and "cortina" as being equivalent.
carToManufacturer[new Car{ Name = "cortina" }] = "Lotus"; // Will set "Cortina"'s value to "Lotus".
Console.WriteLine("Count of items: {0}", carToManufacturer.Count);
// >Count of items: 1
27. 27
27
Controlling String-Key Comparison
● If we use strings as keys (i.e. not a UDT like Car), we can use predefined comparers to compare case insensitively.
– The .Net framework provides a set of predefined StringComparer objects in the type StringComparer.
– Let's rewrite the color code example for case insensitive color names:
– We can do the same with Java's TreeMap managing string-keys case-insensitively using a special Comparator:
– If we like to exploit the sorting of the Map and want the keys to be sorted in descending order, just reverse the Comparator:
// Create a dictionary and specify the case insensitive string comparer in the ctor:
IDictionary<string, int> colorNamesToColorCodes = new SortedDictionary<string, int>(StringComparer.OrdinalIgnoreCase);
colorNamesToColorCodes.Add("Green", 0x00FF00);
// Because of the case insensitive comparison "Green" and "green" are seen as equivalent key objects:
int colorCodeOfGreen = colorNamesToColorCodes["green"];
Console.WriteLine("Color code for Green: {0:X6}", colorCodeOfGreen);
// >Color code for Green: 00FF00
// Create a map and specify the case insensitive string comparator in the ctor:
Map<String, Integer> colorNamesToColorCodes = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
colorNamesToColorCodes.put("Green", 0x00FF00);
// Because of the case insensitive comparison "Green" and "green" are seen as equivalent key objects:
int colorCodeOfGreen = colorNamesToColorCodes.get("green");
System.out.printf("Color code for Green: %06X%n", colorCodeOfGreen);
// >Color code for Green: 00FF00
// Create a map and specify the case insensitive string comparator in the ctor, the sorting should be descending:
Map<String, Integer> colorNamesToColorCodesDescending =
new TreeMap<>(Collections.reverseOrder(String.CASE_INSENSITIVE_ORDER));
● Creating a reversed Comparer by passing an
existing Comparer to Collections.reverseOrder() is
an example of the decorator pattern. A present
Comparer is decorated with extra functionality and
the new object has the same interface than the one
being decorated.