Posts

Showing posts from May, 2020

Spring Data Elasticsearch MappingElasticsearchConverter

Spring Data Elasticsearch MappingElasticsearchConverter  The MappingElasticsearchConverter uses metadata to drive the mapping of objects to documents. The metadata is taken from the entity’s properties which can be annotated. The following annotations are available: @Document: Applied at the class level to indicate this class is a candidate for mapping to the database. The most important attributes are: indexName: the name of the index to store this entity in type: the mapping type. If not set, the lowercased simple name of the class is used. (deprecated since version 4.0) shards: the number of shards for the index. replicas: the number of replicas for the index. refreshIntervall: Refresh interval for the index. Used for index creation. Default value is "1s". indexStoreType: Index storage type for the index. Used for index creation. Default value is "fs". createIndex: Configuration whether to create an index on repository bootstrapping. Default...

Spring Data Elasticsearch @Field

Spring Data Elasticsearch @Field The @Field annotation now supports nearly all of the types that can be used in Elasticsearch. @Document(indexName = "person", type = "dummy") public class Person implements Persistable<Long> {     @Nullable @Id     private Long id;     @Nullable @Field(value = "last-name", type = FieldType.Text, fielddata = true)     private String lastName;      (1)     @Nullable @Field(name = "birth-date", type = FieldType.Date, format = DateFormat.basic_date)     private LocalDate birthDate;  (2)     @CreatedDate     @Nullable @Field(type = FieldType.Date, format = DateFormat.basic_date_time)     private Instant created;      (3)     // other properties, getter, setter } in Elasticsearch this field will be named last-name, this mapping is handled transparently a property for a date without time informat...

Hibernate JPA @FilterJoinTables Example

@FilterJoinTables The @FilterJoinTables annotation is used to group multiple @FilterJoinTable annotations. FilterJoinTables- Add multiple @FilterJoinTable to a collection.

Hibernate JPA @FilterJoinTable Example

@FilterJoinTable The @FilterJoinTable annotation is used to add @Filter capabilities to a join table collection. FilterJoinTable - Add filters to a join table collection. @FilterJoinTable When using the @Filter annotation with collections, the filtering is done against the child entries (entities or embeddables). However, if you have a link table between the parent entity and the child table, then you need to use the @FilterJoinTable to filter child entries according to some column contained in the join table. The @FilterJoinTable annotation can be, therefore, applied to a unidirectional @OneToMany collection as illustrated in the following mapping: Example :  @FilterJoinTable mapping usage @Entity(name = "Client") @FilterDef(     name="firstAccounts",     parameters=@ParamDef(         name="maxOrderId",         type="int"     ) ) public static class Client {     @Id   ...

Hibernate JPA @FilterDefs Example

@FilterDefs The @FilterDefs annotation is used to group multiple @FilterDef annotations. FilterDefs - Array of filter definitions.

Hibernate JPA @FilterDef Example

@FilterDef The @FilterDef annotation is used to specify a @Filter definition (name, default condition and parameter types, if any). FilterDef Filter definition. Defines a name, default condition and parameter types (if any). @Filter mapping entity-level usage @Entity(name = "Account") @Table(name = "account") @FilterDef(     name="activeAccount",     parameters = @ParamDef(         name="active",         type="boolean"     ) ) @Filter(     name="activeAccount",     condition="active_status = :active" ) public static class Account {     @Id     private Long id;     @ManyToOne(fetch = FetchType.LAZY)     private Client client;     @Column(name = "account_type")     @Enumerated(EnumType.STRING)     private AccountType type;     private Double amount;     private Double rate; ...

Hibernate JPA @Filter Example

@Filter The @Filter annotation is used to add filters to an entity or the target entity of a collection. Filter Add filters to an entity or a target entity of a collection. @Filter The @Filter annotation is another way to filter out entities or collections using custom SQL criteria. Unlike the @Where annotation, @Filter allows you to parameterize the filter clause at runtime. Now, considering we have the following Account entity: Example : @Filter mapping entity-level usage @Entity(name = "Account") @Table(name = "account") @FilterDef(     name="activeAccount",     parameters = @ParamDef(         name="active",         type="boolean"     ) ) @Filter(     name="activeAccount",     condition="active_status = :active" ) public static class Account {     @Id     private Long id;     @ManyToOne(fetch = FetchType.LAZY)     private C...

HIbernate JPA @FetchProfiles Example

@FetchProfiles The @FetchProfiles annotation is used to group multiple @FetchProfile annotations. FetchProfiles Collects together multiple fetch profiles.

Hibernate JPA @FetchProfile.FetchOverride Example

@FetchProfile.FetchOverride The @FetchProfile.FetchOverride annotation is used in conjunction with the @FetchProfile annotation, and it’s used for overriding the fetching strategy of a particular entity association. FetchProfile.FetchOverride Descriptor for a particular association override. Fetch profile example @Entity(name = "Employee") @FetchProfile( name = "employee.projects", fetchOverrides = { @FetchProfile.FetchOverride( entity = Employee.class, association = "projects", mode = FetchMode.JOIN ) } )

Hibernate JPA @FetchProfile Example

@FetchProfile The @FetchProfile annotation is used to specify a custom fetching profile, similar to a JPA Entity Graph. FetchProfile Define the fetching strategy profile. Fetch profile example @Entity(name = "Employee") @FetchProfile( name = "employee.projects", fetchOverrides = { @FetchProfile.FetchOverride( entity = Employee.class, association = "projects", mode = FetchMode.JOIN ) } ) session.enableFetchProfile( "employee.projects" ); Employee employee = session.bySimpleNaturalId( Employee.class ).load( username ); Here the Employee is obtained by natural-id lookup and the Employee’s Project data is fetched eagerly. If the Employee data is resolved from cache, the Project data is resolved on its own. However, if the Employee data is not resolved in cache, the Employee and Project data is resolved in one SQL query via join as we saw above.

Java @Schedule Example

@Schedule For example, you are writing code to use a timer service that enables you to run a method at a given time or on a certain schedule, similar to the UNIX cron service. Now you want to set a timer to run a method, doPeriodicCleanup, on the last day of the month and on every Friday at 11:00 p.m. To set the timer to run, create an @Schedule annotation and apply it twice to the doPeriodicCleanup method. The first use specifies the last day of the month and the second specifies Friday at 11p.m., as shown in the following code example: @Schedule(dayOfMonth="last") @Schedule(dayOfWeek="Fri", hour="23") public void doPeriodicCleanup() { ... } The previous example applies an annotation to a method. You can repeat an annotation anywhere that you would use a standard annotation. For example, you have a class for handling unauthorized access exceptions. You annotate the class with one @Alert annotation for managers and another for admins: @Alert(ro...

Java @NonNull Example

@NonNull String str; When you compile the code, including the NonNull module at the command line, the compiler prints a warning if it detects a potential problem, allowing you to modify the code to avoid the error. After you correct the code to remove all warnings, this particular error will not occur when the program runs. You can use multiple type-checking modules where each module checks for a different kind of error. In this way, you can build on top of the Java type system, adding specific checks when and where you want them.

Java @Repeatable Example

@Repeatable  @Repeatable annotation, introduced in Java SE 8, indicates that the marked annotation can be applied more than once to the same declaration or type use. For more information, see Repeating Annotations.

Java @Inherited Example

@Inherited  @Inherited annotation indicates that the annotation type can be inherited from the super class. (This is not true by default.) When the user queries the annotation type and the class has no annotation for this type, the class' superclass is queried for the annotation type. This annotation applies only to class declarations.

Java @Target Example

@Target  @Target annotation marks another annotation to restrict what kind of Java elements the annotation can be applied to. A target annotation specifies one of the following element types as its value: ElementType.ANNOTATION_TYPE can be applied to an annotation type. ElementType.CONSTRUCTOR can be applied to a constructor. ElementType.FIELD can be applied to a field or property. ElementType.LOCAL_VARIABLE can be applied to a local variable. ElementType.METHOD can be applied to a method-level annotation. ElementType.PACKAGE can be applied to a package declaration. ElementType.PARAMETER can be applied to the parameters of a method. ElementType.TYPE can be applied to any element of a class.

Java @Documented Example

@Documented  @Documented annotation indicates that whenever the specified annotation is used those elements should be documented using the Javadoc tool. (By default, annotations are not included in Javadoc.) For more information, see the Javadoc tools page.

Java @Retention Example

@Retention  @Retention annotation specifies how the marked annotation is stored: RetentionPolicy.SOURCE – The marked annotation is retained only in the source level and is ignored by the compiler. RetentionPolicy.CLASS – The marked annotation is retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM). RetentionPolicy.RUNTIME – The marked annotation is retained by the JVM so it can be used by the runtime environment.

Java @FunctionalInterface Example

@FunctionalInterface @FunctionalInterface annotation, introduced in Java SE 8, indicates that the type declaration is intended to be a functional interface, as defined by the Java Language Specification.

Java @SafeVarargs Example

@SafeVarargs  @SafeVarargs annotation, when applied to a method or constructor, asserts that the code does not perform potentially unsafe operations on its varargs parameter. When this annotation type is used, unchecked warnings relating to varargs usage are suppressed.

Java @SuppressWarnings Example

@SuppressWarnings @SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate. In the following example, a deprecated method is used, and the compiler usually generates a warning. In this case, however, the annotation causes the warning to be suppressed.    // use a deprecated method and tell    // compiler not to generate a warning    @SuppressWarnings("deprecation")     void useDeprecatedMethod() {         // deprecation warning         // - suppressed         objectOne.deprecatedMethod();     } Every compiler warning belongs to a category. The Java Language Specification lists two categories: deprecation and unchecked. The unchecked warning can occur when interfacing with legacy code written before the advent of generics. To suppress multiple categories of warnings, use the following syntax: @SuppressWarnings({...

Java @Override Example

@Override  @Override annotation informs the compiler that the element is meant to override an element declared in a superclass. Overriding methods will be discussed in Interfaces and Inheritance.    // mark method as a superclass method    // that has been overridden    @Override    int overriddenMethod() { } While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.

Java @Deprecated Example

@Deprecated  @Deprecated annotation indicates that the marked element is deprecated and should no longer be used. The compiler generates a warning whenever a program uses a method, class, or field with the @Deprecated annotation. When an element is deprecated, it should also be documented using the Javadoc @deprecated tag, as shown in the following example. The use of the at sign (@) in both Javadoc comments and in annotations is not coincidental: they are related conceptually. Also, note that the Javadoc tag starts with a lowercase d and the annotation starts with an uppercase D.    // Javadoc comment follows     /**      * @deprecated      * explanation of why it was deprecated      */     @Deprecated     static void deprecatedMethod() { } }

Spring Events Example

Spring Events Example Spring Data JDBC triggers events that get published to any matching ApplicationListener beans in the application context. For example, the following listener gets invoked before an aggregate gets saved: @Bean public ApplicationListener<BeforeSaveEvent<Object>> loggingSaves() { return event -> { Object entity = event.getEntity(); LOG.info("{} is getting saved."; }; } If you want to handle events only for a specific domain type you may derive your listener from AbstractRelationalEventListener and overwrite one or more of the onXXX methods, where XXX stands for an event type. Callback methods will only get invoked for events related to the domain type and their subtypes so you don’t require further casting. public class PersonLoadListener extends AbstractRelationalEventListener<Person> { @Override protected void onAfterLoad(AfterLoadEvent<Person> personLoad) { LOG.info(personLoad.getEntity()); } }...

Spring PagingAndSortingRepository example

Spring PagingAndSortingRepository example interface PersonRepository extends PagingAndSortingRepository<Person, String> {   List<Person> findByFirstname(String firstname);                                    List<Person> findByFirstnameOrderByLastname(String firstname, Pageable pageable);   Person findByFirstnameAndLastname(String firstname, String lastname);              Person findFirstByLastname(String lastname);                                        @Query("SELECT * FROM person WHERE lastname = :lastname")   List<Person> findByLastname(String lastname);                                    } The method shows a query for a...

Elasticsearch POJO mapping example

Elasticsearch POJO mapping example @Document(indexName = "person") public class Person implements Persistable<Long> {     @Id private Long id;     private String lastName;     private String firstName;     @Field(type = Date)     private Instant createdDate;     private String createdBy     @Field(type = Date)     private Instant lastModifiedDate;     private String lastModifiedBy;     @Override     public boolean isNew() {         return id == null || (createdDate == null && createdBy == null);     } }

Elasticsearch - async search

Elasticsearch - async search Asynchronous search Asynchronous search makes long-running queries feasible and reliable. Async search allows users to run long-running queries in the background, track the query progress, and retrieve partial results as they become available. Async search enables users to more easily search vast amounts of data with no more pesky timeouts. Submit async search API Executes a search request asynchronously. It accepts the same parameters and request body as the search API. POST /sales*/_async_search?size=0 {     "sort" : [       { "date" : {"order" : "asc"} }     ],     "aggs" : {         "sale_date" : {              "date_histogram" : {                  "field" : "date",                  "calendar_interval": "1d"           ...

Java SequenceLayout Example

SequenceLayout A SequenceLayout denotes the repetition of a given layout. In other words, this can be thought of as a sequence of elements similar to an array with the defined element layout. For example, we can create a sequence layout for 25 elements of 64 bits each: SequenceLayout sequenceLayout = MemoryLayout.ofSequence(25,   MemoryLayout.ofValueBits(64, ByteOrder.nativeOrder()));

Java ValueLayout Example

ValueLayout A ValueLayout models a memory layout for basic data types such as integer and floating types. Each value layout has a size and a byte order. We can create a ValueLayout using the ofValueBits method: ValueLayout valueLayout = MemoryLayout.ofValueBits(32, ByteOrder.nativeOrder());

Java - MemoryLayout

MemoryLayout The MemoryLayout class lets us describe the contents of a memory segment. Specifically, it lets us define how the memory is broken up into elements, where the size of each element is provided. This is a bit like describing the memory layout as a concrete type, but without providing a Java class. It's similar to how languages like C++ map their structures to memory. Let's take an example of a cartesian coordinate point defined with the coordinates x and y: int numberOfPoints = 10; MemoryLayout pointLayout = MemoryLayout.ofStruct(   MemoryLayout.ofValueBits(32, ByteOrder.BIG_ENDIAN).withName("x"),   MemoryLayout.ofValueBits(32, ByteOrder.BIG_ENDIAN).withName("y") ); SequenceLayout pointsLayout =   MemoryLayout.ofSequence(numberOfPoints, pointLayout); Here, we've defined a layout made of two 32-bit values named x and y. This layout can be used with a SequenceLayout to make something similar to an array, in this case with 10 in...

Java MemoryAddress Example

MemoryAddress A MemoryAddress is an offset within a memory segment. It's commonly obtained using the baseAddress method: MemoryAddress address = MemorySegment.allocateNative(100).baseAddress(); A memory address is used to perform operations such as retrieving data from memory on the underlying memory segment.

Java MemorySegment Example

MemorySegment A memory segment is a contiguous region of memory. This can be either heap or off-heap memory. And, there are several ways to obtain a memory segment. A memory segment backed by native memory is known as a native memory segment. It's created using one of the overloaded allocateNative methods. Let's create a native memory segment of 200 bytes: MemorySegment memorySegment = MemorySegment.allocateNative(200); A memory segment can also be backed by an existing heap-allocated Java array. For example, we can  create an array memory segment from an array of long: MemorySegment memorySegment = MemorySegment.ofArray(new long[100]); Additionally, a memory segment can be backed by an existing Java ByteBuffer. This is known as a buffer memory segment: MemorySegment memorySegment = MemorySegment.ofByteBuffer(ByteBuffer.allocateDirect(200)); Alternatively, we can use a memory-mapped file. This is known as a mapped memory segment. Let's define a 200-byte mem...

Java - Foreign-Memory Access API

The Foreign-Memory Access API was proposed by JEP 370 and targeted to Java 14 in late 2019 as an incubating API. This JEP proposes to incorporate refinements based on feedback, and re-incubate the API in Java 15. The following changes will be considered for inclusion: A rich VarHandle combinator API, to customize memory access var handles; Targeted support for parallel processing of a memory segment via the Spliterator interface; Enhanced support for mapped memory segments (e.g., MappedMemorySegment::force); Safe API points to support serial confinement (e.g., to transfer thread ownership between two threads); and Unsafe API points to manipulate and dereference addresses coming from, e.g., native calls, or to wrap such addresses into synthetic memory segments. Goals Generality: A single API should be able to operate on various kinds of foreign memory (e.g., native memory, persistent memory, managed heap memory, etc.). Safety: It should not be possible for the API to underm...

Hibernate JPA @Fetch Example

@Fetch The @Fetch annotation is used to specify the Hibernate specific FetchMode (e.g. JOIN, SELECT, SUBSELECT) used for the currently annotated association. Fetch define the fetching strategy used for the given association. The @Fetch annotation mapping Besides the FetchType.LAZY or FetchType.EAGER JPA annotations, you can also use the Hibernate-specific @Fetch annotation that accepts one of the following FetchModes: SELECT The association is going to be fetched using a secondary select for each individual entity, collection, or join load. This mode can be used for either FetchType.EAGER or FetchType.LAZY. JOIN Use an outer join to load the related entities, collections or joins when using direct fetching. This mode can only be used for FetchType.EAGER. SUBSELECT Available for collections only. When accessing a non-initialized collection, this fetch mode will trigger loading all elements of all collections of the same role for all owners associated with the persistenc...

Hibernate JPA @DynamicUpdate Example

@DynamicUpdate The @DynamicUpdate annotation is used to specify that the UPDATE SQL statement should be generated whenever an entity is modified. By default, Hibernate uses a cached UPDATE statement that sets all table columns. When the entity is annotated with the @DynamicUpdate annotation, the PreparedStatement is going to include only the columns whose values have been changed. For updating, should this entity use dynamic sql generation where only changed columns get referenced in the prepared sql statement? Note, for re-attachment of detached entities this is not possible without select-before-update being enabled. Dynamic updates To enable dynamic updates, you need to annotate the entity with the @DynamicUpdate annotation: Example : Product entity mapping @Entity(name = "Product") @DynamicUpdate public static class Product { @Id private Long id; @Column private String name; @Column private String description; @Column(name = "price...

Hibernate JPA @DynamicInsert Example

@DynamicInsert The @DynamicInsert annotation is used to specify that the INSERT SQL statement should be generated whenever an entity is to be persisted. By default, Hibernate uses a cached INSERT statement that sets all table columns. When the entity is annotated with the @DynamicInsert annotation, the PreparedStatement is going to include only the non-null columns. DynamicInsert For inserting, should this entity use dynamic sql generation where only non-null columns get referenced in the prepared sql statement?

Hibernate JPA @DiscriminatorOptions Example

@DiscriminatorOptions The @DiscriminatorOptions annotation is used to provide the force and insert Discriminator properties. DiscriminatorOptions Optional annotation to express Hibernate specific discriminator properties. Discriminator The discriminator column contains marker values that tell the persistence layer what subclass to instantiate for a particular row. Hibernate Core supports the following restricted set of types as discriminator column: String, char, int, byte, short, boolean(including yes_no, true_false). Use the @DiscriminatorColumn to define the discriminator column as well as the discriminator type. The enum DiscriminatorType used in javax.persistence.DiscriminatorColumn only contains the values STRING, CHAR and INTEGER which means that not all Hibernate supported types are available via the @DiscriminatorColumn annotation. You can also use @DiscriminatorFormula to express in SQL a virtual discriminator column. This is particularly useful when the discrimin...

Hibernate JPA @DiscriminatorFormula Example

@DiscriminatorFormula The @DiscriminatorFormula annotation is used to specify a Hibernate @Formula to resolve the inheritance discriminator value. DiscriminatorFormula Used to apply a Hibernate formula (derived value) as the inheritance discriminator "column". Used in place of the JPA DiscriminatorColumn when a formula is wanted. To be placed on the root entity. Single Table discriminator formula @Entity(name = "Account") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorFormula( "case when debitKey is not null " + "then 'Debit' " + "else ( " + "   case when creditKey is not null " + "   then 'Credit' " + "   else 'Unknown' " + "   end ) " + "end " ) public static class Account { @Id private Long id; private String owner; private BigDecimal balance; private BigDecimal interestRate; //Getters and setter...

Hibernate JPA @CreationTimestamp Example

@CreationTimestamp The @CreationTimestamp annotation is used to specify that the currently annotated temporal type must be initialized with the current JVM timestamp value. Marks a property as the creation timestamp of the containing entity. The property value will be set to the current VM date exactly once when saving the owning entity for the first time. Supported property types: Date Calendar Date Time Timestamp Instant LocalDate LocalDateTime LocalTime MonthDay OffsetDateTime OffsetTime Year YearMonth ZonedDateTime @CreationTimestamp annotation The @CreationTimestamp annotation instructs Hibernate to set the annotated entity attribute with the current timestamp value of the JVM when the entity is being persisted. The supported property types are: java.util.Date java.util.Calendar java.sql.Date java.sql.Time java.sql.Timestamp Example : @CreationTimestamp mapping example @Entity(name = "Event") public static class Event { @Id ...

Hibernate JPA @ColumnTransformers Example

@ColumnTransformers The @ColumnTransformers annotation iis used to group multiple @ColumnTransformer annotations.

Hibernate JPA @ColumnTransformer Example

@ColumnTransformer The @ColumnTransformer annotation is used to customize how a given column value is read from or written into the database. ColumnTransformer Custom SQL expression used to read the value from and write a value to a column. Use for direct object loading/saving as well as queries. The write expression must contain exactly one '?' placeholder for the value. For example: read="decrypt(credit_card_num)" write="encrypt(?)" @ColumnTransformer example @Entity(name = "Employee") public static class Employee { @Id private Long id; @NaturalId private String username; @Column(name = "pswd") @ColumnTransformer( read = "decrypt( 'AES', '00', pswd  )", write = "encrypt('AES', '00', ?)" ) private String password; private int accessLevel; @ManyToOne(fetch = FetchType.LAZY) private Department department; @ManyToMany(mappedBy = "employees...

Intellij shortcuts keys : Recompile 'class'

Intellij shortcuts keys : Recompile 'class name' Compile a single file or class keys - ( Ctrl+Shift+F9 )

For-each takes precedence over traditional for or while

For-each takes precedence over traditional for or while Before Java 1.5, a collection must be looped. for (Iterator i = c.iterator(); i.hasNext(); ) {   doSomething((Element) i.next()); // (No generics before 1.5) } The loop array is like this for (int i = 0; i < a.length; i++) {   doSomething(a[i]); } These practices are better than while, but there are still too many places you may change to your index variable or iterator So the recommended way in this book is as follows for (Element e : elements) {   doSomething(e); } The colon stands for each element e in the set Not only is it the same in performance (even better), it wo n’t give you a chance to write bugs The author also gave an example of wanting to print each card of a deck enum Suit { CLUB, DIAMOND, HEART, SPADE } enum Rank { ACE, DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING } Collection<Suit> suits = Arrays.asList(Suit.values()); Collection<R...

Introduction to JAVA virtual machine

Image
In 1991, Sun MicroSystems (acquired by Oracle in 2010) wanted to develop new technologies that could control smart appliances (microwave oven TV) or allow smart appliances to communicate with each other. Called Green Project The difficulty of this project is that the target is home appliances. There are many restrictions as follows 1. Less memory for embedded systems: So programs must consume as little memory as possible 2. Cross-platform: we don't want a program to be compiled after each device is compiled to execute. We want to compile once and run everywhere 3. Security: The process of transferring programs between devices must be ensured that the device will not be damaged even if it is maliciously modified 4. Multi-thread support Translator Initially, the team planned to use C ++, but C ++ could not meet the cross-platform requirements. For example, Hello.exe that you compiled in the Linux system cannot be directly executed by Window So although C ++ was very ...

Prefer try-with-resources to try-finally

The Java libraries include many resources that must be closed manually by invoking a close method. Examples include InputStream, OutputStream, and java.sql.Connection. Closing resources is often overlooked by clients, with predictably dire performance consequences. While many of these resources use finalizers as a safety net, finalizers don’t work very well (Item 8). Historically, a try-finally statement was the best way to guarantee that a resource would be closed properly, even in the face of an exception or return: // try-finally - No longer the best way to close resources! static String firstLineOfFile(String path) throws IOException { BufferedReader br = new BufferedReader(new FileReader(path)); try { return br.readLine(); } finally { br.close(); } } This may not look bad, but it gets worse when you add a second resource: // try-finally is ugly when used with more than one resource! static void copy(String src, String dst) throws IOException { InputStream in = new Fi...

Always override hashCode when you override equals

You must override hashCode in every class that overrides equals. If you fail to do so, your class will violate the general contract for hashCode, which will prevent it from functioning properly in collections such as HashMap and HashSet. Here is the contract, adapted from the Object specification : • When the hashCode method is invoked on an object repeatedly during an execution of an application, it must consistently return the same value, provided no information used in equals comparisons is modified. This value need not remain consistent from one execution of an application to another. • If two objects are equal according to the equals(Object) method, then calling hashCode on the two objects must produce the same integer result. • If two objects are unequal according to the equals(Object) method, it is not required that calling hashCode on each of the objects must produce distinct results. However, the programmer should be aware that producing distinct results for unequal ob...