The document provides a summary of key Java concepts including:
1) Primitive types like int, boolean, and char. Operators like assignment, binary, and unary. Casting between types.
2) Common classes like Scanner for input, Math for functions, String for string methods. Collections like List, Set, Map and their usage.
3) Other concepts covered include if/else statements, loops, arrays, functions, classes/objects, polymorphism with inheritance/interfaces, and generics.
Beginning Haskell, Dive In, Its Not That Scary!priort
Haskell can get a bit of a reputation for being this lofty, academic, difficult to learn language. This talk aims to dispel this myth and offer an introduction to this beautiful and pragmatic language. From the point of view of someone who has been functional programming in Scala and Clojure for a while now, but who has, more recently been taking a dive into Haskell, this talk will give a basic introduction to Haskell. Hopefully it will encourage anyone who hasn't tried functional programming in Haskell to dive in too and give it a go.
The talk will be a whistle stop tour of some functional programming fundamentals in Haskell from basic data structures, logic constructs, functional transformations, recursion to some of the basics of Haskell's type system with data declarations and type classes.
Function Programming in Scala.
A lot of my examples here comes from the book
Functional programming in Scala By Paul Chiusano and Rúnar Bjarnason, It is a good book, buy it.
19. Java data structures algorithms and complexityIntro C# Book
In this chapter we will compare the data structures we have learned so far by the performance (execution speed) of the basic operations (addition, search, deletion, etc.). We will give specific tips in what situations what data structures to use.
Beginning Haskell, Dive In, Its Not That Scary!priort
Haskell can get a bit of a reputation for being this lofty, academic, difficult to learn language. This talk aims to dispel this myth and offer an introduction to this beautiful and pragmatic language. From the point of view of someone who has been functional programming in Scala and Clojure for a while now, but who has, more recently been taking a dive into Haskell, this talk will give a basic introduction to Haskell. Hopefully it will encourage anyone who hasn't tried functional programming in Haskell to dive in too and give it a go.
The talk will be a whistle stop tour of some functional programming fundamentals in Haskell from basic data structures, logic constructs, functional transformations, recursion to some of the basics of Haskell's type system with data declarations and type classes.
Function Programming in Scala.
A lot of my examples here comes from the book
Functional programming in Scala By Paul Chiusano and Rúnar Bjarnason, It is a good book, buy it.
19. Java data structures algorithms and complexityIntro C# Book
In this chapter we will compare the data structures we have learned so far by the performance (execution speed) of the basic operations (addition, search, deletion, etc.). We will give specific tips in what situations what data structures to use.
Chapter 22. Lambda Expressions and LINQIntro C# Book
In this chapter we will become acquainted with some of the advanced capabilities of the C# language. To be more specific, we will pay attention on how to make queries to collections, using lambda expressions and LINQ, and how to add functionality to already created classes, using extension methods. We will get to know the anonymous types, describe their usage briefly and discuss lambda expressions and show in practice how most of the built-in lambda functions work. Afterwards, we will pay more attention to the LINQ syntax – we will learn what it is, how it works and what queries we can build with it. In the end, we will get to know the meaning of the keywords in LINQ, and demonstrate their capabilities with lots of examples.
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
Все началось давно, еще в школе, классе эдак 7. Тогда учитель математики впервые произнесла фразу: "Игрек равно эф от икс". В то время я и не догадывался что это самое "эф от икс", является базовым принципом функционального программирования, да и не только функционального.
Functional Programming, Reactive Programming, Transducers, MapReduce и многое другое, так или иначе корнями уходит в то самое, незамысловатое f(x). Это настолько серьезная часть программирования, что ежеминутно, если не ежесекундно, по всему миру на клавиатуре нажимаются клавиши f, u, n, c, t, i, o, n. И нажимаются они именно в этой последовательности.
Пора принять тот факт, что без функционального программирования, программирования не существует!
Пора разобраться. Пора понять для чего нужны функции в программирование, как они должны работать и чем они могут быть полезны в ежедневной работе.
A tour of Python: slides from presentation given in 2012.
[Some slides are not properly rendered in SlideShare: the original is still available at http://www.aleksa.org/2015/04/python-presentation_7.html.]
In this chapter we will learn about arrays as a way to work with sequences of elements of the same type. We will explain what arrays are, how we declare, create, instantiate and use them. We will examine one-dimensional and multidimensional arrays. We will learn different ways to iterate through the array, read from the standard input and write to the standard output. We will give many example exercises, which can be solved using arrays and we will show how useful they really are.
Some languages, like SML, Haskell, and Scala, have built-in support for pattern matching, which is a generic way of branching based on the structure of data.
While not without its drawbacks, pattern matching can help eliminate a lot of boilerplate, and it's often cited as a reason why functional programming languages are so concise.
In this talk, John A. De Goes talks about the differences between built-in patterns, and so-called first-class patterns (which are "do-it-yourself" patterns implemented using other language features).
Unlike built-in patterns, first-class patterns aren't magical, so you can store them in variables and combine them in lots of interesting ways that aren't always possible with built-in patterns. In addition, almost every programming language can support first-class patterns (albeit with differing levels of effort and type-safety).
During the talk, you'll watch as a mini-pattern matching library is developed, and have the opportunity to follow along and build your own pattern matching library in the language of your choice.
In this chapter we will analyze more complex data structures like dictionaries and sets, and their implementations with hash-tables and balanced trees. We will explain in more details what hashing and hash-tables mean and why they are such an important part of programming. We will discuss the concept of "collisions" and how they might happen when implementing hash-tables. Also we will offer you different types of approaches for solving this type of issues. We will look at the abstract data structure set and explain how it can be implemented with the ADTs dictionary and balanced search tree. Also we will provide you with examples that illustrate the behavior of these data structures with real world examples.
Monads, also known as Kleisli triples in Category Theory, are an (endo-)functor together with two natural transformations, which are surprisingly useful in pure languages like Haskell, but this talk will NOT reference monads. Ever. (Well, at least not in this talk.)
Instead what I intend to impress upon an audience of newcomers to Haskell is the wide array of freely available libraries most of which are liberally licensed open source software, intuitive package management, practical build tools, reasonable documentation (when you know how to read it and where to find it), interactive shell (or REPL), mature compiler, stable runtime, testing tools that will blow your mind away, and a small but collaborative and knowledgeable community of developers. Oh, and some special features of Haskell - the language - too!
Great Scott! C# 7 is almost out!
Time to hop into the DeLorean with Doc Brown. If my calculations are correct, when this baby hits 88 miles per hour, we'll be traveling back to the future with C# 7. Switches? Where we're going, we don't need Switches we got Pattern Matching. Just hold on for one second. Let's get this straight, in the future Tuples will be usable! This will beg the questions. Where are we? When are we? We are in the future and we now have Local Functions and Records.
You'll walk away with a sense of where C# is going and how you can learn about its new features today by looking back to the future. This is heavy.
Chapter 22. Lambda Expressions and LINQIntro C# Book
In this chapter we will become acquainted with some of the advanced capabilities of the C# language. To be more specific, we will pay attention on how to make queries to collections, using lambda expressions and LINQ, and how to add functionality to already created classes, using extension methods. We will get to know the anonymous types, describe their usage briefly and discuss lambda expressions and show in practice how most of the built-in lambda functions work. Afterwards, we will pay more attention to the LINQ syntax – we will learn what it is, how it works and what queries we can build with it. In the end, we will get to know the meaning of the keywords in LINQ, and demonstrate their capabilities with lots of examples.
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
Все началось давно, еще в школе, классе эдак 7. Тогда учитель математики впервые произнесла фразу: "Игрек равно эф от икс". В то время я и не догадывался что это самое "эф от икс", является базовым принципом функционального программирования, да и не только функционального.
Functional Programming, Reactive Programming, Transducers, MapReduce и многое другое, так или иначе корнями уходит в то самое, незамысловатое f(x). Это настолько серьезная часть программирования, что ежеминутно, если не ежесекундно, по всему миру на клавиатуре нажимаются клавиши f, u, n, c, t, i, o, n. И нажимаются они именно в этой последовательности.
Пора принять тот факт, что без функционального программирования, программирования не существует!
Пора разобраться. Пора понять для чего нужны функции в программирование, как они должны работать и чем они могут быть полезны в ежедневной работе.
A tour of Python: slides from presentation given in 2012.
[Some slides are not properly rendered in SlideShare: the original is still available at http://www.aleksa.org/2015/04/python-presentation_7.html.]
In this chapter we will learn about arrays as a way to work with sequences of elements of the same type. We will explain what arrays are, how we declare, create, instantiate and use them. We will examine one-dimensional and multidimensional arrays. We will learn different ways to iterate through the array, read from the standard input and write to the standard output. We will give many example exercises, which can be solved using arrays and we will show how useful they really are.
Some languages, like SML, Haskell, and Scala, have built-in support for pattern matching, which is a generic way of branching based on the structure of data.
While not without its drawbacks, pattern matching can help eliminate a lot of boilerplate, and it's often cited as a reason why functional programming languages are so concise.
In this talk, John A. De Goes talks about the differences between built-in patterns, and so-called first-class patterns (which are "do-it-yourself" patterns implemented using other language features).
Unlike built-in patterns, first-class patterns aren't magical, so you can store them in variables and combine them in lots of interesting ways that aren't always possible with built-in patterns. In addition, almost every programming language can support first-class patterns (albeit with differing levels of effort and type-safety).
During the talk, you'll watch as a mini-pattern matching library is developed, and have the opportunity to follow along and build your own pattern matching library in the language of your choice.
In this chapter we will analyze more complex data structures like dictionaries and sets, and their implementations with hash-tables and balanced trees. We will explain in more details what hashing and hash-tables mean and why they are such an important part of programming. We will discuss the concept of "collisions" and how they might happen when implementing hash-tables. Also we will offer you different types of approaches for solving this type of issues. We will look at the abstract data structure set and explain how it can be implemented with the ADTs dictionary and balanced search tree. Also we will provide you with examples that illustrate the behavior of these data structures with real world examples.
Monads, also known as Kleisli triples in Category Theory, are an (endo-)functor together with two natural transformations, which are surprisingly useful in pure languages like Haskell, but this talk will NOT reference monads. Ever. (Well, at least not in this talk.)
Instead what I intend to impress upon an audience of newcomers to Haskell is the wide array of freely available libraries most of which are liberally licensed open source software, intuitive package management, practical build tools, reasonable documentation (when you know how to read it and where to find it), interactive shell (or REPL), mature compiler, stable runtime, testing tools that will blow your mind away, and a small but collaborative and knowledgeable community of developers. Oh, and some special features of Haskell - the language - too!
Great Scott! C# 7 is almost out!
Time to hop into the DeLorean with Doc Brown. If my calculations are correct, when this baby hits 88 miles per hour, we'll be traveling back to the future with C# 7. Switches? Where we're going, we don't need Switches we got Pattern Matching. Just hold on for one second. Let's get this straight, in the future Tuples will be usable! This will beg the questions. Where are we? When are we? We are in the future and we now have Local Functions and Records.
You'll walk away with a sense of where C# is going and how you can learn about its new features today by looking back to the future. This is heavy.
This presentation considers certain specific features of C++11 and additions to STL library (uniform initialization, new containers and methods, move semantics).
Presentation by Taras Protsiv (Software Engineer, GlobalLogic), Kyiv, delivered at GlobalLogic C++ TechTalk in Lviv, September 18, 2014.
More details -
http://www.globallogic.com.ua/press-releases/lviv-cpp-techtalk-coverage
Kotlin is a modern statically typed programming language which was made a first-class language for writing Android Apps by Google in 2017. Since then it has grown into popularity and many apps from hottest startups to 500 fortune companies are built using Kotlin. This talk will deep dive into Kotlin and modern android architecture for writing apps faster and in a better way.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
The field of Information retrieval (IR) is currently undergoing a transformative shift, at least partly due to the emerging applications of generative AI to information access. In this talk, we will deliberate on the sociotechnical implications of generative AI for information access. We will argue that there is both a critical necessity and an exciting opportunity for the IR community to re-center our research agendas on societal needs while dismantling the artificial separation between the work on fairness, accountability, transparency, and ethics in IR and the rest of IR research. Instead of adopting a reactionary strategy of trying to mitigate potential social harms from emerging technologies, the community should aim to proactively set the research agenda for the kinds of systems we should build inspired by diverse explicitly stated sociotechnical imaginaries. The sociotechnical imaginaries that underpin the design and development of information access technologies needs to be explicitly articulated, and we need to develop theories of change in context of these diverse perspectives. Our guiding future imaginaries must be informed by other academic fields, such as democratic theory and critical theory, and should be co-developed with social science scholars, legal scholars, civil rights and social justice activists, and artists, among others.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Let's dive deeper into the world of ODC! Ricardo Alves (OutSystems) will join us to tell all about the new Data Fabric. After that, Sezen de Bruijn (OutSystems) will get into the details on how to best design a sturdy architecture within ODC.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Epistemic Interaction - tuning interfaces to provide information for AI support
The java language cheat sheet
1. THE JAVA LANGUAGE CHEAT SHEET
Primitive Types:
INTEGER: byte(8bit),short(16bit),int(32bit),
long(64bit),DECIM:float(32bit),double(64bit)
,OTHER: boolean(1bit), char (Unicode)
HEX:0x1AF,BINARY:0b00101,LONG:8888888888888L
CHAR EXAMPLES: ‘a’,’n’,’t’,’’’,’’,’”’
Primitive Operators
Assignment Operator: = (ex: int a=5,b=3; )
Binary Operators (two arguments): + - * / %
Unary Operators: + - ++ --
Boolean Not Operator (Unary): !
Boolean Binary: == != > >= < <=
Boolean Binary Only: && ||
Bitwise Operators: ~ & ^ | << >> >>>
Ternary Operator: bool?valtrue:valfalse;
Casting, Conversion
int x = (int)5.5; //works for numeric types
int x = Integer.parseInt(“123”);
float y = Float.parseFloat(“1.5”);
int x = Integer.parseInt(“7A”,16); //fromHex
String hex = Integer.toString(99,16);//toHex
//Previous lines work w/ binary, other bases
java.util.Scanner, input, output
Scanner sc = new Scanner(System.in);
int i = sc.nextInt(); //stops at whitespace
String line = sc.nextLine(); //whole line
System.out.println(“bla”); //stdout
System.err.print(“bla”); //stderr,no newline
java.lang.Number types
Integer x = 5; double y = x.doubleValue();
double y = (double)x.intValue();
//Many other methods for Long, Double, etc
java.lang.String Methods
//Operator +, e.g. “fat”+”cat” -> “fatcat”
boolean equals(String other);
int length();
char charAt(int i);
String substring(int i, int j); //j not incl
boolean contains(String sub);
boolean startsWith(String pre);
boolean endsWith(String post);
int indexOf(String p); //-1 if not found
int indexOf(String p, int i); //start at i
int compareTo(String t);
//“a”.compareTo(“b”) -> -1
String replaceAll(String str, String find);
String[] split(String delim);
StringBuffer, StringBuilder
StringBuffer is synchronized StringBuilder
(Use StringBuilder unless multithreaded)
Use the .apend( xyz ) methods to concat
toString() converts back to String
java.lang.Math
Math.abs(NUM),Math.ceil(NUM),Math.floor(NUM)
,Math.log(NUM),Math.max(A,B),Math.min(C,D),
Math.pow(A,B),Math.round(A),Math.random()
IF STATEMENTS:
if( boolean_value ) { STATEMENTS }
else if( bool ) { STATEMENTS }
else if( ..etc ) { STATEMENTS }
else { STATEMENTS }
//curly brackets optional if one line
LOOPS:
while( bool ) { STATEMENTS }
for(INIT;BOOL;UPDATE) { STATEMENTS }
//1INIT 2BOOL 3STATEMENTS 4UPDATE 5->Step2
do{ STATEMENTS }while( bool );
//do loops run at least once before checking
break; //ends enclosing loop (exit loop)
continue; //jumps to bottom of loop
ARRAYS:
int[] x = new int[10]; //ten zeros
int[][] x = new int[5][5]; //5 by 5 matrix
int[] x = {1,2,3,4};
x.length; //int expression length of array
int[][] x = {{1,2},{3,4,5}}; //ragged array
String[] y = new String[10]; //10 nulls
//Note that object types are null by default
//loop through array:
for(int i=0;i<arrayname.length;i++) {
//use arrayname[i];
}
//for-each loop through array
int[] x = {10,20,30,40};
for(int v : x) {
//v cycles between 10,20,30,40
}
//Loop through ragged arrays:
for(int i=0;i<x.length;i++)
for(int j=0;j<x[i].length;j++) {
//CODE HERE
}
//Note, multi-dim arrays can have nulls
//in many places, especially object arrays:
Integer[][] x = {{1,2},{3,null},null};
FUNCTIONS / METHODS:
Static Declarations:
public static int functionname( … )
private static double functionname( … )
static void functionname( … )
Instance Declarations:
public void functionname( … )
private int functionname( … )
Arguments, Return Statement:
int myfunc(int arg0, String arg1) {
return 5; //type matches int myfunc
}
//Non-void methods must return before ending
//Recursive functions should have an if
//statement base-case that returns at once
CLASS/OBJECT TYPES:
INSTANTIATION:
public class Ball {//only 1 public per file
//STATIC FIELDS/METHODS
private static int numBalls = 0;
public static int getNumBalls() {
return numBalls;
}
public static final int BALLRADIUS = 5;
//INSTANCE FIELDS
private int x, y, vx, vy;
public boolean randomPos = false;
//CONSTRUCTORS
public Ball(int x, int y, int vx, int vy)
{
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
numBalls++;
}
Ball() {
x = Math.random()*100;
y = Math.random()*200;
randomPos = true;
}
//INSTANCE METHODS
public int getX(){ return x; }
public int getY(){ return y; }
public int getVX(){ return vx; }
public int getVY(){ return vy; }
public void move(){ x+=vx; y+=vy; }
public boolean touching(Ball other) {
float dx = x-other.x;
float dy = y-other.y;
float rr = BALLRADIUS;
return Math.sqrt(dx*dx+dy*dy)<rr;
}
}
//Example Usage:
public static void main(String[] args) {
Ball x = new Ball(5,10,2,2);
Ball y = new Ball();
List<Ball> balls = new ArrayList<Ball>();
balls.add(x); balls.add(y);
for(Ball b : balls) {
for(Ball o : balls) {
if(b != o) { //compares references
boolean touch = b.touching(o);
}
}
}
}
Downloaded by RR PP (rohitpatel13579@gmail.com)
lOMoARcPSD|9377264
2. POLYMORPHISM:
Single Inheritance with “extends”
class A{ }
class B extends A{ }
abstract class C { }
class D extends C { }
class E extends D
Abstract methods
abstract class F {
abstract int bla();
}
class G extends F {
int bla() { //required method
return 5;
}
}
Multiple Inheritance of interfaces with
“implements” (fields not inherited)
interface H {
void methodA();
boolean methodB(int arg);
}
interface I extends H{
void methodC();
}
interface K {}
class J extends F implements I, K {
int bla() { return 5; } //required from F
void methodA(){} //required from H
boolean methodB(int a) { //req from A
return 1;
}
void methodC(){} //required from I
}
Type inference:
A x = new B(); //OK
B y = new A(); //Not OK
C z = new C(); //Cannot instantiate abstract
//Method calls care about right hand type
(the instantiated object)
//Compiler checks depend on left hand type
GENERICS:
class MyClass<T> {
T value;
T getValue() { return value; }
}
class ExampleTwo<A,B> {
A x;
B y;
}
class ExampleThree<A extends List<B>,B> {
A list;
B head;
}
//Note the extends keyword here applies as
well to interfaces, so A can be an interface
that extends List<B>
JAVA COLLECTIONS:
List<T>: Similar to arrays
ArrayList<T>: Slow insert into middle
//ArrayList has fast random access
LinkedList<T>: slow random access
//LinkedList fast as queue/stack
Stack: Removes and adds from end
List Usage:
boolean add(T e);
void clear(); //empties
boolean contains(Object o);
T get(int index);
T remove(int index);
boolean remove(Object o);
//remove uses comparator
T set(int index, E val);
Int size();
List Traversal:
for(int i=0i<x.size();i++) {
//use x.get(i);
}
//Assuming List<T>:
for(T e : x) {
//use e
}
Queue<T>: Remove end, Insert beginning
LinkedList implements Queue
Queue Usage:
T element(); // does not remove
boolean offer(T o); //adds
T peek(); //pike element
T poll(); //removes
T remove(); //like poll
Traversal: for(T e : x) {}
Set<T>: uses Comparable<T> for uniqueness
TreeSet<T>, items are sorted
HashSet<T>, not sorted, no order
LinkedHashSet<T>, ordered by insert
Usage like list: add, remove, size
Traversal: for(T e : x) {}
Map<K,V>: Pairs where keys are unique
HashMap<K,V>, no order
LinkedHashMap<K,V> ordered by insert
TreeMap<K,V> sorted by keys
V get(K key);
Set<K> keySet(); //set of keys
V put(K key, V value);
V remove(K key);
Int size();
Collection<V> values(); //all values
Traversal: for-each w/ keyset/values
java.util.PriorityQueue<T>
A queue that is always automatically sorted
using the comparable function of an object
public static void main(String[] args) {
Comparator<String> cmp= new LenCmp();
PriorityQueue<String> queue =
new PriorityQueue<String>(10, cmp);
queue.add("short");
queue.add("very long indeed");
queue.add("medium");
while (queue.size() != 0)
System.out.println(queue.remove());
}
class LenCmp implements Comparator<String> {
public int compare(String x, String y){
return x.length() – y.length();
}
}
java.util.Collections algorithms
Sort Example:
//Assuming List<T> x
Collections.sort(x); //sorts with comparator
Sort Using Comparator:
Collections.sort(x, new Comparator<T>{
public int compareTo(T a, T b) {
//calculate which is first
//return -1, 0, or 1 for order:
return someint;
}
}
Example of two dimensional array sort:
public static void main(final String[] a){
final String[][] data = new String[][] {
new String[] { "20090725", "A" },
new String[] { "20090726", "B" },
new String[] { "20090727", "C" },
new String[] { "20090728", "D" } };
Arrays.sort(data,
new Comparator<String[]>() {
public int compare(final String[]
entry1, final String[] entry2) {
final String time1 = entry1[0];
final String time2 = entry2[0];
return time1.compareTo(time2);
}
});
for (final String[] s : data) {
System.out.println(s[0]+" "+s[1]);
}
}
}
More collections static methods:
Collections.max( … ); //returns maximum
Collections.min( … ); //returns maximum
Collections.copy( A, B); //A list into B
Collections.reverse( A ); //if A is list
Downloaded by RR PP (rohitpatel13579@gmail.com)
lOMoARcPSD|9377264