Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
What are the differences between a HashMap and a Hashtable in Java?
There are several differences between HashMap and Hashtable in Java: Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones. Hashtable does not allow null keys or values. HaRead more
There are several differences between
HashMap
andHashtable
in Java:Hashtable
is synchronized, whereasHashMap
is not. This makesHashMap
better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.Hashtable
does not allownull
keys or values.HashMap
allows onenull
key and any number ofnull
values.LinkedHashMap
, so in the event that you’d want predictable iteration order (which is insertion order by default), you could easily swap out theHashMap
for aLinkedHashMap
. This wouldn’t be as easy if you were usingHashtable
.Since synchronization is not an issue for you, I’d recommend
See lessHashMap
. If synchronization becomes an issue, you may also look atConcurrentHashMap
.How to generate random integers within a specific range in Java?
There are several differences between HashMap and Hashtable in Java: Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones. Hashtable does not allow null keys or values. HaRead more
There are several differences between
HashMap
andHashtable
in Java:Hashtable
is synchronized, whereasHashMap
is not. This makesHashMap
better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.Hashtable
does not allownull
keys or values.HashMap
allows onenull
key and any number ofnull
values.LinkedHashMap
, so in the event that you’d want predictable iteration order (which is insertion order by default), you could easily swap out theHashMap
for aLinkedHashMap
. This wouldn’t be as easy if you were usingHashtable
.Since synchronization is not an issue for you, I’d recommend
See lessHashMap
. If synchronization becomes an issue, you may also look atConcurrentHashMap
.Create ArrayList from array
Java 7+ In Java 1.7 or later, the standard way to do this (generate a basic non-cryptographically secure random integer in the range [min, max]) is as follows: import java.util.concurrent.ThreadLocalRandom; // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive int randoRead more
Java 7+
In Java 1.7 or later, the standard way to do this (generate a basic non-cryptographically secure random integer in the range [min, max]) is as follows:
See the relevant JavaDoc. This approach has the advantage of not needing to explicitly initialize a java.util.Random instance, which can be a source of confusion and error if used inappropriately.
However, conversely with ThreadLocalRandom there is no way to explicitly set the seed so it can be difficult to reproduce results in situations where that is useful such as testing or saving game states or similar.
Java 17+
As of Java 17, the psuedorandom number generating classes in the standard library implement the
RandomGenerator
interface. See the linked JavaDoc for more information. For example, if a cryptographically strong random number generator is desired, theSecureRandom
class can be used.Earlier Java
Before Java 1.7, the standard way to do this is as follows:
See the relevant JavaDoc. In practice, the java.util.Random class is often preferable to java.lang.Math.random().
In particular, there is no need to reinvent the random integer generation wheel when there is a straightforward API within the standard library to accomplish the task.
See lessCreate ArrayList from array
If You Can, Use Guava It's worth pointing out the Guava way, which greatly simplifies these shenanigans: Usage For an Immutable List Use the ImmutableList class and its of() and copyOf() factory methods (elements can't be null): List<String> il = ImmutableList.of("string", "elements"); // fromRead more
If You Can, Use Guava
It’s worth pointing out the Guava way, which greatly simplifies these shenanigans:
Usage
For an Immutable List
Use the
ImmutableList
class and itsof()
andcopyOf()
factory methods (elements can’t be null):For A Mutable List
Use the
Lists
class and itsnewArrayList()
factory methods:Please also note the similar methods for other data structures in other classes, for instance in
Sets
.Why Guava?
The main attraction could be to reduce the clutter due to generics for type-safety, as the use of the Guava factory methods allow the types to be inferred most of the time. However, this argument holds less water since Java 7 arrived with the new diamond operator.
But it’s not the only reason (and Java 7 isn’t everywhere yet): the shorthand syntax is also very handy, and the methods initializers, as seen above, allow to write more expressive code. You do in one Guava call what takes 2 with the current Java Collections.
If You Can’t…
For an Immutable List
Use the JDK’s
Arrays
class and itsasList()
factory method, wrapped with aCollections.unmodifiableList()
:Note that the returned type for
asList()
is aList
using a concreteArrayList
implementation, but it is NOTjava.util.ArrayList
. It’s an inner type, which emulates anArrayList
but actually directly references the passed array and makes it “write through” (modifications are reflected in the array).It forbids modifications through some of the
List
API’s methods by way of simply extending anAbstractList
(so, adding or removing elements is unsupported), however it allows calls toset()
to override elements. Thus this list isn’t truly immutable and a call toasList()
should be wrapped withCollections.unmodifiableList()
.See the next step if you need a mutable list.
For a Mutable List
Same as above, but wrapped with an actual
java.util.ArrayList
:For Educational Purposes: The Good ol’ Manual Way
See lessCreate ArrayList from array
You can use the following instruction: new ArrayList<>(Arrays.asList(array));
You can use the following instruction:
See lessWhat is the difference between Promises and Observables?
Both Promises and Observables provide us with abstractions that help us deal with the asynchronous nature of our applications. The difference between them was pointed out clearly by Günter and @Relu. Since a code snippet is worth a thousand words, let’s go through the below example to understand theRead more
Both
Promises
andObservables
provide us with abstractions that help us deal with the asynchronous nature of our applications. The difference between them was pointed out clearly by Günter and @Relu.Since a code snippet is worth a thousand words, let’s go through the below example to understand them easier.
Angular uses Rx.js Observables instead of promises for dealing with HTTP.
Suppose that you are building a search function that should instantly show you results as you type. It sounds familiar, but there are a lot of challenges that come with that task.
The demo will simply consist of two files:
app.ts
andwikipedia-service.ts
. In a real world scenario, we would most likely split things further up, though.Below is a Promise-based implementation that doesn’t handle any of the described edge cases.
wikipedia-service.ts
We are injecting the
Jsonp
service to make a GET request against the Wikipedia API with a given search term. Notice that we calltoPromise
in order to get from anObservable<Response>
to aPromise<Response>
. Eventually end up with aPromise<Array<string>>
as the return type of our search method.app.ts
There is not much of a surprise here either. We inject our
WikipediaService
and expose its functionality via a search method to the template. The template simply binds to keyup and callssearch(term.value)
.We unwrap the result of the Promise that the search method of the WikipediaService returns and expose it as a simple array of strings to the template so that we can have
*ngFor
loop through it and build up a list for us.See the example of Promise-based implementation on Plunker
Where Observables really shine
Let’s change our code to not hammer the endpoint with every keystroke, but instead only send a request when the user stopped typing for 400 ms
To unveil such super powers, we first need to get an
Observable<string>
that carries the search term that the user types in. Instead of manually binding to the keyup event, we can take advantage of Angular’sformControl
directive. To use this directive, we first need to import theReactiveFormsModule
into our application module.app.ts
Once imported, we can use formControl from within our template and set it to the name “term”.
In our component, we create an instance of
FormControl
from@angular/form
and expose it as a field under the name term on our component.Behind the scenes, term automatically exposes an
Observable<string>
as propertyvalueChanges
that we can subscribe to. Now that we have anObservable<string>
, overcoming the user input is as easy as callingdebounceTime(400)
on ourObservable
. This will return a newObservable<string>
that will only emit a new value when there haven’t been coming new values for 400 ms.It would be a waste of resources to send out another request for a search term that our application already shows the results for. All we have to do to achieve the desired behavior is to call the
See lessdistinctUntilChanged
operator right after we calleddebounceTime(400)
What is the difference between Promises and Observables?
Promise A Promise handles a single event when an async operation completes or fails. Note: There are Promise libraries out there that support cancellation, but ES6 Promise doesn't so far. Observable An Observable is like a Stream (in many languages) and allows you to pass zero or more events where tRead more
Promise
A
Promise
handles a single event when an async operation completes or fails.Note: There are
Promise
libraries out there that support cancellation, but ES6Promise
doesn’t so far.Observable
An
Observable
is like aStream
(in many languages) and allows you to pass zero or more events where the callback is called for each event.Often
Observable
is preferred overPromise
because it provides the features ofPromise
and more. WithObservable
it doesn’t matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case.Observable
also has the advantage overPromise
to be cancellable. If the result of an HTTP request to a server or some other expensive async operation isn’t needed anymore, theSubscription
of anObservable
allows you to cancel the subscription, while aPromise
will eventually call the success or failed callback even when you don’t need the notification or the result it provides anymore.While a
Promise
starts immediately, anObservable
only starts if you subscribe to it. This is why Observables are called lazy.Observable provides operators like
map
,forEach
,reduce
, … similar to an arrayThere are also powerful operators like
retry()
, orreplay()
, … that are often quite handy. A list of operators shipped with rxjsLazy execution allows you to build up a chain of operators before the observable is executed by subscribing, to do a more declarative kind of programming.
See lessCan’t bind to ‘ngModel’ since it isn’t a known property of ‘input’?
For using [(ngModel)] in Angular 2, 4 & 5+, you need to import FormsModule from Angular form... Also, it is in this path under forms in the Angular repository on GitHub: angular / packages / forms / src / directives / ng_model.ts Probably this is not a very pleasurable for the AngularJS developeRead more
For using
[(ngModel)]
in Angular 2, 4 & 5+, you need to import FormsModule from Angular form…Also, it is in this path under forms in the Angular repository on GitHub:
Probably this is not a very pleasurable for the AngularJS developers as you could use ng-model everywhere anytime before, but as Angular tries to separate modules to use whatever you’d like you to want to use at the time, ngModel is in FormsModule now.
Also, if you are using ReactiveFormsModule it needs to import it too.
So simply look for app.module.ts and make sure you have
FormsModule
imported in…Also, these are the current starting comments for Angular4
ngModel
in FormsModule:If you’d like to use your input, not in a form, you can use it with
See lessngModelOptions
and make standalone true…Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’?
Yes, that's it. In the app.module.ts file, I just added: import { FormsModule } from '@angular/forms'; [...] @NgModule({ imports: [ [...] FormsModule ], [...] })
Yes, that’s it. In the app.module.ts file, I just added:
See lessHow to programmatically navigate using React Router?
The useHistory() hook is now deprecated. If you are using React Router 6, the proper way to navigate programmatically is as follows: import { useNavigate } from "react-router-dom"; function HomeButton() { const navigate = useNavigate(); function handleClick() { navigate("/home"); } return ( <buttRead more
The
useHistory()
hook is now deprecated. If you are using React Router 6, the proper way to navigate programmatically is as follows:There is a new
useHistory
hook in React Router >5.1.0 if you are using React >16.8.0 and functional components.With v4 of React Router, there are three approaches that you can take to programmatic routing within components.
withRouter
higher-order component.<Route>
context
.React Router is mostly a wrapper around the
history
library.history
handles interaction with the browser’swindow.history
for you with its browser and hash histories. It also provides a memory history which is useful for environments that don’t have a global history. This is particularly useful in mobile app development (react-native
) and unit testing with Node.A
history
instance has two methods for navigating:push
andreplace
. If you think of thehistory
as an array of visited locations,push
will add a new location to the array andreplace
will replace the current location in the array with the new one. Typically you will want to use thepush
method when you are navigating.In earlier versions of React Router, you had to create your own
history
instance, but in v4 the<BrowserRouter>
,<HashRouter>
, and<MemoryRouter>
components will create a browser, hash, and memory instances for you. React Router makes the properties and methods of thehistory
instance associated with your router available through the context, under therouter
object.1. Use the
withRouter
higher-order componentThe
withRouter
higher-order component will inject thehistory
object as a prop of the component. This allows you to access thepush
andreplace
methods without having to deal with thecontext
.2. Use composition and render a
<Route>
The
<Route>
component isn’t just for matching locations. You can render a pathless route and it will always match the current location. The<Route>
component passes the same props aswithRouter
, so you will be able to access thehistory
methods through thehistory
prop.3. Use the context*
But you probably should not
The last option is one that you should only use if you feel comfortable working with React’s context model (React’s Context API is stable as of v16).
1 and 2 are the simplest choices to implement, so for most use cases, they are your best bets.
See less